-2

How do I clear the old pinned marker location and place it on new location? Am using Google Javascript API map with autocomplete search. When I search for a location the marker will pin on the location in map, if I type new location it will add another marker, but I don't want it that way, I want it to add marker to new location and clear the old pinned location.

Sample image

enter image description here

From the above image, I want only one green marker on current typed location, if location changes it will be placed only on new one not create multiple markers.

   var autocomplete;
      var countryRestrict = {'country': 'us'};
      var MARKER_PATH = 'https://developers.google.com/maps/documentation/javascript/images/marker_green';
   
      var componentForm = {
        route: 'long_name',
        locality: 'long_name',
        administrative_area_level_1: 'short_name',
        country: 'long_name'
      };
   
   var initOptions = { 
    'current': { 
     center: {lat: 2.9248795999999997, lng: 101.63688289999999}, 
     zoom: 15, 
     country: 'MY', 
     componentRestrictions: {'country': 'us'} 
    } 
   };
  
    var customLabel = {
        restaurant: {
          label: 'R'
        },
        bar: {
          label: 'B'
        }
      };
   
 function initGoogleMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
          zoom: initOptions['current'].zoom,
          center: initOptions['current'].center,
          mapTypeControl: false,
          panControl: false,
          zoomControl: false,
          streetViewControl: false,
    clickableIcons: false,
    fullscreenControl: false
        });
  
  var input = document.getElementById('SeachLOcationToBuy');
        autocomplete = new google.maps.places.Autocomplete(input);
  autocomplete.bindTo('bounds', map);
  /*map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);*/
  
  autocomplete.setComponentRestrictions({'country': initOptions['current'].country}); 
  
  var markerLetter = String.fromCharCode('A'.charCodeAt(0) + (1 % 26));
  var markerIcon = MARKER_PATH + markerLetter + '.png';
  
  var infoWindow = new google.maps.InfoWindow;
  
  autocomplete.addListener('place_changed', function() {
   
          var place = autocomplete.getPlace();
          if (!place.geometry) {
            return;
          }
    
          if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
          } else {
            map.setCenter(place.geometry.location); 
            map.setZoom(17);
          }
    
    var point = new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng());
   var marker = new google.maps.Marker({
     map: map,
     position: point,
     icon: markerIcon,
     label: 'P'
   });

    fillInAddress(place);
    document.getElementById('UpdateFoodAddress').disabled = false;
    document.getElementById('full_address').value = input.value;
     
  
          /*Set the position of the marker using the place ID and location.*/
          marker.setPlace({
            placeId: place.place_id,
            location: place.geometry.location
          });
          marker.setVisible(true);
        });
  
   downloadUrl("_api/setGeoXmlLocation.php?geolocate=true", function(data) {
   var xml = data.responseXML;
   var markers = xml.documentElement.getElementsByTagName('marker');
   var counts = xml.documentElement.getElementsByTagName('counter')[0].childNodes[0];
  
   Array.prototype.forEach.call(markers, function(markerElem) {
     var id = markerElem.getAttribute('id');
     var name = markerElem.getAttribute('name');
     var logo = markerElem.getAttribute('logo');
     var address = markerElem.getAttribute('address');
     var type = markerElem.getAttribute('type');
     var page = markerElem.getAttribute('page');
     var point = new google.maps.LatLng(
      parseFloat(markerElem.getAttribute('lat')),
      parseFloat(markerElem.getAttribute('lng'))
      );
      
     var infowincontent = document.createElement('div');
     var strong = document.createElement('strong');
     var img = document.createElement('img');
     var imgbox = document.createElement('div');
     var br = document.createElement('br');
     var span = document.createElement('span');
     var text = document.createElement('text');
     /*WINDOW*/
     infowincontent.setAttribute("class", "app-map-info-window");
     text.textContent = address;
     infowincontent.appendChild(text);
     var icon = customLabel[type] || {};
     var marker = new google.maps.Marker({
    map: map,
    position: point,
    label:  icon.label
     });

     marker.addListener('click', function() {
    infoWindow.setContent(infowincontent);
    infoWindow.open(map, marker);
     });
   });
    });
        }


 function fillInAddress(place) {

        for (var component in componentForm) {
          document.getElementById(component).value = '';
          document.getElementById(component).disabled = false;
        }
        for (var i = 0; i < place.address_components.length; i++) {
          var addressType = place.address_components[i].types[0];
          if (componentForm[addressType]) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType).value = val;
          }
        }
    }
   
 function geolocate() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var geolocation = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
            var circle = new google.maps.Circle({
              center: geolocation,
              radius: position.coords.accuracy
            });
            autocomplete.setBounds(circle.getBounds());
          });
        }
    }
   
    function downloadUrl(url, callback) {
        var request = window.ActiveXObject ?
            new ActiveXObject('Microsoft.XMLHTTP') :
            new XMLHttpRequest;

        request.onreadystatechange = function() {
          if (request.readyState == 4) {
            request.onreadystatechange = doNothing;
            callback(request, request.status);
          }
        };

        request.open('GET', url, true);
        request.send(null);
    }

    function doNothing(){
  
 }
initGoogleMap();
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAkkzv-gkVsQSAUDOjUdEBmXVqmaDphVjc&libraries=places&callback=initMap"></script>
<input id="SeachLOcationToBuy" class="map-form-control form-control" type="text" name="setMyNewAddress" placeholder="Enter your address" onFocus="geolocate()" value=""/>
    <div class="PageBodyContainerMap">
  <span class="container">
   <span class="GeoMap">
    <div id="map"></div>
    <div id="infowindow-content">
      <span id="place-name"  class="title"></span><br>
      Place ID <span id="place-id"></span><br>
      <span id="place-address"></span>
    </div>
   </span>
  </span>
 </div>
jasie
  • 2,192
  • 10
  • 39
  • 54
Peter
  • 1,860
  • 2
  • 18
  • 47
  • Did you try marker.setMap(null) -> https://stackoverflow.com/questions/44281555/google-maps-delete-all-markers-and-then-create-new – jasie Jan 14 '19 at 13:41
  • @jasie yes but it didn't work – Peter Jan 14 '19 at 13:46
  • 2
    That should work if you do this just before you create a new marker... – jasie Jan 14 '19 at 13:52
  • 1
    @Peter this site is not a free coding service. Pasting 200 lines of code and saying it doesn't work as you expect is not the way to ask. Please read on [How to ask](https://stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – MrUpsidown Jan 14 '19 at 14:38
  • possible duplicate of [Google Maps Nearby Search (Show Selected nearby markers only with autocomplete)](https://stackoverflow.com/questions/36453547/google-maps-nearby-search-show-selected-nearby-markers-only-with-autocomplete) – geocodezip Jan 14 '19 at 14:46

1 Answers1

-1

1) Create a global accessible array var markers = [].

2) Push all references of the markers you create into that array.

3) When you want to remove one of these markers, you have just have to remove that marker from the array.

An example:

var markers = []; //Global Marker array to keep references
 var marker = new google.maps.Marker({
        position: {lat: lat, lng: lng},
        icon: icon,
        map: map
    });
    markers.push(marker);

removeMarker: function () {
    for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(null);
    }
    markers = [];
},

You have now just to transfer this to your code. Next time it would be a good Idea to just post relevant code.

Hope it helps.

el solo lobo
  • 973
  • 11
  • 23
  • 1) This question has been asked and answered already multiple times and therefore should probably be closed 2) You are providing a few lines of code, out of any context, and as it is, your code doesn't do anything – MrUpsidown Jan 14 '19 at 15:23