简体   繁体   中英

How to removed pinned marker and set it new location Google Javascript API

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

在此处输入图片说明

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM