Google maps delete all markers and then create new

Viktor

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.net/ehsLLg26/

Here my code:

        <script type="text/javascript">
                function initAutocomplete() {      
                    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.

user7138697

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 initAutocomplete() {
  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.com/maps/api/js?key=AIzaSyBZbI5EJHVyNPd07tdhGgIODBpuqCePlIw&libraries=places&callback=initAutocomplete">


</script>

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Google maps clear all markers before placing new one

分類Dev

How to delete markers from my own google maps

分類Dev

Google Maps API 3 - Show All Markers on Screen, but Keep Centerpoint

分類Dev

How to get all markers in google-maps-react

分類Dev

ReactJS and Google Maps - Displaying Markers

分類Dev

Placing Circles instead of Markers in google maps

分類Dev

Google Maps: infobox turns up behind markers?

分類Dev

Google Maps fit markers in custom bounds

分類Dev

Google maps API markers content hide by default

分類Dev

How to hide/show groups of markers by category with Google Maps in Android?

分類Dev

How to Add Google Maps with Multiple Markers Showing Infowindows on Load and on Click

分類Dev

Setting listeners to groups of markers using Google Maps API

分類Dev

Google Map API V3 - infowindows @ markers on 2 maps

分類Dev

Google Maps API 3 Load Markers from MySQL from current position

分類Dev

Get Markers Addresses in Input fields using Drag-able Google Maps API V3

分類Dev

Map markers not rendering - Google Maps Javascript API v3 In Phonegap

分類Dev

Adding Multiple Markers in real time google maps v2 android

分類Dev

How to manage Markers well using google maps api v2 on android

分類Dev

`vue2-google-maps`で` new google.maps.Marker() `を使用する方法

分類Dev

Google maps v2 not displayed on new activity

分類Dev

Google 3D Earth How to find the center point from all the markers and set center view

分類Dev

Get all Google Map v3 markers loaded from GeoJSON

分類Dev

Close all info windows google maps API V3?

分類Dev

Unable to create a new project in the Google Developer Console

分類Dev

Unable to create a new project on google developer console

分類Dev

How to apply CSS to Here Maps API Markers

分類Dev

Draw circles around multiple markers in Maps

分類Dev

Table doesn't update after create, edit or delete new row

分類Dev

Remove all Markers from map

Related 関連記事

  1. 1

    Google maps clear all markers before placing new one

  2. 2

    How to delete markers from my own google maps

  3. 3

    Google Maps API 3 - Show All Markers on Screen, but Keep Centerpoint

  4. 4

    How to get all markers in google-maps-react

  5. 5

    ReactJS and Google Maps - Displaying Markers

  6. 6

    Placing Circles instead of Markers in google maps

  7. 7

    Google Maps: infobox turns up behind markers?

  8. 8

    Google Maps fit markers in custom bounds

  9. 9

    Google maps API markers content hide by default

  10. 10

    How to hide/show groups of markers by category with Google Maps in Android?

  11. 11

    How to Add Google Maps with Multiple Markers Showing Infowindows on Load and on Click

  12. 12

    Setting listeners to groups of markers using Google Maps API

  13. 13

    Google Map API V3 - infowindows @ markers on 2 maps

  14. 14

    Google Maps API 3 Load Markers from MySQL from current position

  15. 15

    Get Markers Addresses in Input fields using Drag-able Google Maps API V3

  16. 16

    Map markers not rendering - Google Maps Javascript API v3 In Phonegap

  17. 17

    Adding Multiple Markers in real time google maps v2 android

  18. 18

    How to manage Markers well using google maps api v2 on android

  19. 19

    `vue2-google-maps`で` new google.maps.Marker() `を使用する方法

  20. 20

    Google maps v2 not displayed on new activity

  21. 21

    Google 3D Earth How to find the center point from all the markers and set center view

  22. 22

    Get all Google Map v3 markers loaded from GeoJSON

  23. 23

    Close all info windows google maps API V3?

  24. 24

    Unable to create a new project in the Google Developer Console

  25. 25

    Unable to create a new project on google developer console

  26. 26

    How to apply CSS to Here Maps API Markers

  27. 27

    Draw circles around multiple markers in Maps

  28. 28

    Table doesn't update after create, edit or delete new row

  29. 29

    Remove all Markers from map

ホットタグ

アーカイブ