简体   繁体   English

如何删除固定标记并将其设置为新位置 Google Javascript API

[英]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?如何清除旧的固定marker位置并将其放置在新位置? Am using Google Javascript API map with autocomplete search.我正在使用带有自动完成搜索功能的 Google Javascript API 地图。 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.当我搜索一个位置时,标记将固定在地图中的位置上,如果我输入新位置,它将添加另一个marker ,但我不希望那样,我希望它将marker添加到新位置并清除旧位置固定位置。

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 = [] . 1) 创建一个全局可访问数组var markers = []

2) Push all references of the markers you create into that array. 2)将您创建的标记的所有引用推送到该数组中。

3) When you want to remove one of these markers, you have just have to remove that marker from the array. 3) 当您想要删除这些标记之一时,您只需从数组中删除该标记。

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.希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Google Map API 如何为当前位置设置标记 - Google Map API how to set marker for current location 我们如何在 google map api 中通过 javascript 设置标记标签内容? - how we set marker label content by javascript in google map api? Google Maps JavaScript API中标记位置更改时发生的事件 - Event when marker location changes in Google Maps JavaScript API 自动更新Google Maps JavaScript API上的标记位置 - Auto-update marker location on Google Maps Javascript API 如何为谷歌地图标记设置新坐标? - How to set new coordinate for google maps marker? Google Maps Api Javascript-如何通过文本位置(非经/纬度)定位标记 - Google Maps Api Javascript - How to position a marker by text location (not lat/long) 如何使用JavaScript在Google地图中设置标记 - How to set marker in google map using javascript Google会在没有位置的情况下将地图设置为默认位置 - Google maps if no location set marker to default location 在不使用自动完成或标记事件的情况下将位置加载到文本框中时,如何在Google地图中设置标记位置? - how to set marker location in google map when location is loaded into a textbox without using autocomplete or marker events? 如何使用Google Maps API在用户位置显示地图和标记 - How to use google maps api to display map and marker at users location
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM