admin管理员组

文章数量:1405141

I'm working to create a map, that by default loads the address and shows tha marker and place address in search box, that works fine. But I need to add the click event that will delete all markers first and then put the marker. As so far I was develop script that do all I need. But when user clicks on map, the searchbox gets place address but the old marker doesn't delete and new marker doesn't appears in the click location.

Here my working example code: /

Here my code:

        <script type="text/javascript">
                function initAutoplete() {      
                    var myOptions = {
                        zoom: 15,
                        mapTypeId: google.maps.MapTypeId.ROADMAP, 
                        mapTypeControl: false
                    }                       

                    var map;
                    var marker;
                    var geocoder = new google.maps.Geocoder();
                    var address = document.getElementById('pac-input').value;
                    var infowindow = new google.maps.InfoWindow();                                              

                    geocoder.geocode( { address: address}, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK && results.length) {
                            if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {

                                //create map
                                map = new google.maps.Map(document.getElementById("map"), myOptions);

                                //center map
                                map.setCenter(results[0].geometry.location);

                                //create marker
                                marker = new google.maps.Marker({
                                    position: results[0].geometry.location,
                                    map: map,
                                    title: document.getElementById('pac-input').value,
                                });                                                                       

                                // Create the search box and link it to the UI element.
                                var input = document.getElementById('pac-input');
                                var searchBox = new google.maps.places.SearchBox(input);
                                map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

                                // Bias the SearchBox results towards current maps viewport.
                                map.addListener('bounds_changed', function() {
                                    searchBox.setBounds(map.getBounds());
                                });

                                var markers = [];
                                // Listen for the event fired when the user selects a prediction and retrieve
                                // more details for that place.
                                searchBox.addListener('places_changed', function() {
                                    var places = searchBox.getPlaces();

                                    if (places.length == 0) {
                                        return;
                                    }    

                                    // Clear out the old markers.
                                    markers.forEach(function(marker) {
                                        marker.setMap(null);
                                    });
                                    marker.setMap(null);
                                    markers = [];

                                    // For each place, get the icon, name and location.
                                    var bounds = new google.maps.LatLngBounds();
                                    places.forEach(function(place) {
                                        var icon = {
                                            url: place.icon,
                                            size: new google.maps.Size(71, 71),
                                            origin: new google.maps.Point(0, 0),
                                            anchor: new google.maps.Point(17, 34),
                                            scaledSize: new google.maps.Size(25, 25)
                                        };

                                        // Create a marker for each place.
                                        markers.push(new google.maps.Marker({
                                            map: map,
                                            title: place.name,
                                            position: place.geometry.location
                                        }));

                                        if (place.geometry.viewport) {
                                            // Only geocodes have viewport.
                                            bounds.union(place.geometry.viewport);
                                        } else {
                                            bounds.extend(place.geometry.location);
                                        }
                                        });
                                    map.fitBounds(bounds);
                                });                                    

                                google.maps.event.addListener(map, 'click', function(event) {
                                    geocoder.geocode({
                                        'latLng': event.latLng
                                        }, function(results, status) {
                                            if (status == google.maps.GeocoderStatus.OK) {
                                                if (results[0]) {
                                                    document.getElementById('pac-input').value = results[0].formatted_address;                                                     
                                                }
                                            }
                                        });                                              
                                    placeMarker(event.latLng);
                                });                                                                                                          

                                function placeMarker(location) {                                        
                                    if (marker) {                                            
                                        marker.setPosition(location);                                           
                                    } else {
                                        marker = new google.maps.Marker({
                                            position: place.geometry.location, 
                                            map: map,
                                            title: place.name,
                                        });
                                    }
                                }                                    
                            }
                        } 
                        else {
                            $('#map').css({'height' : '15px'});
                            $('#map').html("Oops! address could not be found, please make sure the address is correct.");
                            resizeIframe();
                        }
                    });                        

                    function resizeIframe() {
                        var me = window.name;
                        if (me) {
                            var iframes = parent.document.getElementsByName(me);
                            if (iframes && iframes.length == 1) {
                                height = document.body.offsetHeight;
                                iframes[0].style.height = height + "px";
                            }
                        }
                    }
                    }
                </script>

How to reproduce issue: 1. Run the script 2. In search box type any address, then click enter 3. After the marker is added, click to nearby location Result: The old marker is not deleted and the new marker is not show. Expected result: Old marker deletes and the new marker appear.

I'm working to create a map, that by default loads the address and shows tha marker and place address in search box, that works fine. But I need to add the click event that will delete all markers first and then put the marker. As so far I was develop script that do all I need. But when user clicks on map, the searchbox gets place address but the old marker doesn't delete and new marker doesn't appears in the click location.

Here my working example code: https://jsfiddle/ehsLLg26/

Here my code:

        <script type="text/javascript">
                function initAutoplete() {      
                    var myOptions = {
                        zoom: 15,
                        mapTypeId: google.maps.MapTypeId.ROADMAP, 
                        mapTypeControl: false
                    }                       

                    var map;
                    var marker;
                    var geocoder = new google.maps.Geocoder();
                    var address = document.getElementById('pac-input').value;
                    var infowindow = new google.maps.InfoWindow();                                              

                    geocoder.geocode( { address: address}, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK && results.length) {
                            if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {

                                //create map
                                map = new google.maps.Map(document.getElementById("map"), myOptions);

                                //center map
                                map.setCenter(results[0].geometry.location);

                                //create marker
                                marker = new google.maps.Marker({
                                    position: results[0].geometry.location,
                                    map: map,
                                    title: document.getElementById('pac-input').value,
                                });                                                                       

                                // Create the search box and link it to the UI element.
                                var input = document.getElementById('pac-input');
                                var searchBox = new google.maps.places.SearchBox(input);
                                map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

                                // Bias the SearchBox results towards current maps viewport.
                                map.addListener('bounds_changed', function() {
                                    searchBox.setBounds(map.getBounds());
                                });

                                var markers = [];
                                // Listen for the event fired when the user selects a prediction and retrieve
                                // more details for that place.
                                searchBox.addListener('places_changed', function() {
                                    var places = searchBox.getPlaces();

                                    if (places.length == 0) {
                                        return;
                                    }    

                                    // Clear out the old markers.
                                    markers.forEach(function(marker) {
                                        marker.setMap(null);
                                    });
                                    marker.setMap(null);
                                    markers = [];

                                    // For each place, get the icon, name and location.
                                    var bounds = new google.maps.LatLngBounds();
                                    places.forEach(function(place) {
                                        var icon = {
                                            url: place.icon,
                                            size: new google.maps.Size(71, 71),
                                            origin: new google.maps.Point(0, 0),
                                            anchor: new google.maps.Point(17, 34),
                                            scaledSize: new google.maps.Size(25, 25)
                                        };

                                        // Create a marker for each place.
                                        markers.push(new google.maps.Marker({
                                            map: map,
                                            title: place.name,
                                            position: place.geometry.location
                                        }));

                                        if (place.geometry.viewport) {
                                            // Only geocodes have viewport.
                                            bounds.union(place.geometry.viewport);
                                        } else {
                                            bounds.extend(place.geometry.location);
                                        }
                                        });
                                    map.fitBounds(bounds);
                                });                                    

                                google.maps.event.addListener(map, 'click', function(event) {
                                    geocoder.geocode({
                                        'latLng': event.latLng
                                        }, function(results, status) {
                                            if (status == google.maps.GeocoderStatus.OK) {
                                                if (results[0]) {
                                                    document.getElementById('pac-input').value = results[0].formatted_address;                                                     
                                                }
                                            }
                                        });                                              
                                    placeMarker(event.latLng);
                                });                                                                                                          

                                function placeMarker(location) {                                        
                                    if (marker) {                                            
                                        marker.setPosition(location);                                           
                                    } else {
                                        marker = new google.maps.Marker({
                                            position: place.geometry.location, 
                                            map: map,
                                            title: place.name,
                                        });
                                    }
                                }                                    
                            }
                        } 
                        else {
                            $('#map').css({'height' : '15px'});
                            $('#map').html("Oops! address could not be found, please make sure the address is correct.");
                            resizeIframe();
                        }
                    });                        

                    function resizeIframe() {
                        var me = window.name;
                        if (me) {
                            var iframes = parent.document.getElementsByName(me);
                            if (iframes && iframes.length == 1) {
                                height = document.body.offsetHeight;
                                iframes[0].style.height = height + "px";
                            }
                        }
                    }
                    }
                </script>

How to reproduce issue: 1. Run the script 2. In search box type any address, then click enter 3. After the marker is added, click to nearby location Result: The old marker is not deleted and the new marker is not show. Expected result: Old marker deletes and the new marker appear.

Share Improve this question edited May 31, 2017 at 10:15 Viktor asked May 31, 2017 at 9:56 ViktorViktor 1431 silver badge6 bronze badges 1
  • developers.google./maps/documentation/javascript/examples/… – Vagner Lucas Gomes Commented May 31, 2017 at 10:47
Add a ment  | 

1 Answer 1

Reset to default 4

You need to change:

      // Clear out the old markers.
      markers.forEach(function(marker) {
          marker.setMap(null);
      });
      marker.setMap(null);
      markers = [];

to

  // Clear out the old markers.
  markers.forEach(function(marker) {
      marker.setMap(null);
  });

and make google.maps.event.addListener(map, 'click', function(event) {

google.maps.event.addListener(map, 'click', function(event) {
      geocoder.geocode({
        'latLng': event.latLng
      }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[0]) {
            markers.forEach(function(marker) {
              marker.setMap(null);
            })
            document.getElementById('pac-input').value = results[0].formatted_address;
          }
        }
      });
      placeMarker(event.latLng);
    });

EDIT:

Replace:

    // Create a marker for each place.
    markers.push(new google.maps.Marker({
        map: map,
        title: place.name,
        position: place.geometry.location
}));

with:

placeMarker(place.geometry.location)

JSFiddle:

function initAutoplete() {
  var myOptions = {
    zoom: 5,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: false
  }

  var map;
  var marker;
  var geocoder = new google.maps.Geocoder();
  var address = document.getElementById('pac-input').value;
  var infowindow = new google.maps.InfoWindow();
  var markers = [];

  geocoder.geocode({
    address: address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK && results.length) {
      if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {

        //create map
        map = new google.maps.Map(document.getElementById("map"), myOptions);

        //center map
        map.setCenter(results[0].geometry.location);

        //create marker
        marker = new google.maps.Marker({
          position: results[0].geometry.location,
          map: map,
          title: document.getElementById('pac-input').value,
        });

        // Create the search box and link it to the UI element.
        var input = document.getElementById('pac-input');
        var searchBox = new google.maps.places.SearchBox(input);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

        // Bias the SearchBox results towards current maps viewport.
        map.addListener('bounds_changed', function() {
          searchBox.setBounds(map.getBounds());
        });

        
        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener('places_changed', function() {
          var places = searchBox.getPlaces();

          if (places.length == 0) {
            return;
          }

          // Clear out the old markers.
          markers.forEach(function(marker) {
            marker.setMap(null);
          });

          // For each place, get the icon, name and location.
          var bounds = new google.maps.LatLngBounds();
          places.forEach(function(place) {
            var icon = {
              url: place.icon,
              size: new google.maps.Size(71, 71),
              origin: new google.maps.Point(0, 0),
              anchor: new google.maps.Point(17, 34),
              scaledSize: new google.maps.Size(25, 25)
            };
							placeMarker(place.geometry.location)
            if (place.geometry.viewport) {
              // Only geocodes have viewport.
              bounds.union(place.geometry.viewport);
            } else {
              bounds.extend(place.geometry.location);
            }
          });
          map.fitBounds(bounds);
        });

        google.maps.event.addListener(map, 'click', function(event) {
          geocoder.geocode({
            'latLng': event.latLng
          }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
              if (results[0]) {
                markers.forEach(function(marker) {
                  marker.setMap(null);
                });
                document.getElementById('pac-input').value = results[0].formatted_address;
                          placeMarker(event.latLng);
              }
            }
          });
        });

        function placeMarker(location) {
          if (marker) {
            marker.setPosition(location);
          } else {
            marker = new google.maps.Marker({
              position: place.geometry.location,
              map: map,
              title: place.name,
            });
          }
        }
      }
    } else {
      $('#map').css({
        'height': '15px'
      });
      $('#map').html("Oops! address could not be found, please make sure the address is correct.");
      resizeIframe();
    }
  });

  function resizeIframe() {
    var me = window.name;
    if (me) {
      var iframes = parent.document.getElementsByName(me);
      if (iframes && iframes.length == 1) {
        height = document.body.offsetHeight;
        iframes[0].style.height = height + "px";
      }
    }
  }
}
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis./maps/api/js?key=AIzaSyBZbI5EJHVyNPd07tdhGgIODBpuqCePlIw&libraries=places&callback=initAutoplete">


</script>

本文标签: javascriptGoogle maps delete all markers and then create newStack Overflow