【发布时间】:2019-10-11 18:55:22
【问题描述】:
通过这段代码,我可以根据当前位置数据在地图上放置一个标记。
之后,当用户点击地图时,我想显示一个标记并设置新坐标。 (标记前删除)
但是当我点击地图时,我看到我有两个标记,而旧标记没有 已删除。
如何为第一个标记设置新坐标?
注意:如果我没有第一个标记,我应该通过点击创建第一个标记。(我这样做)
地图:
<div id="map"></div>
<script>
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 28.961856892883443,
lng: 50.83683013916016
},
zoom: 15,
gestureHandling: 'greedy',
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var location = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
marker = new google.maps.Marker({
position: location,
map: map
});
infoWindow.open(map);
map.setCenter(location);
}, function () {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, location) {
alert("Error");
infoWindow.open(map);
}
// New marker by click on map
$(document).ready(function () {
var marker;
function placeMarker(location) {
if (marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map
});
}
}
google.maps.event.addListener(map, 'click', function (event) {
placeMarker(event.latLng);
});
});
</script>
<script async defer
src = "https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&language=fa&callback=initMap" >
</script>
注意:我只想要地图中的一个标记。
【问题讨论】:
-
你是怎么做到的(将第二个 sn-p 添加到第一个中)?请提供证明问题的minimal reproducible example(在您的问题中)。我的fiddle 工作正常。
-
您如何尝试在您的问题中结合两个 sn-ps 代码?请提供一个minimal reproducible example 来证明您的问题。如果它们是分开的,我会收到一个错误 (
google is not defined)。 -
第一个代码在正文中,第二个代码在正文之后。当我将第二个代码放在第一个代码中时出现此错误。我只想更改坐标第一个标记。
-
我认为你没有使用 $(document).ready(function() 并且这个错误就是为此。我更改了我的代码。请再次检查..
-
你为什么使用 jquery (
$(document).ready)?
标签: javascript google-maps google-maps-markers