JS
var map;
function initialize()
{
var myCenter=new google.maps.LatLng(13.001294, 77.661736);
var mapProp = {
center:myCenter,
zoom:15,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
});
document.getElementById("latt").innerHTML = location.lat();
document.getElementById("long").innerHTML = location.lng();
}
google.maps.event.addDomListener(window, 'load', initialize);
HTML
<div id="googleMap" style="width:500px;height:380px;"></div>
<p id="latt"></p>
<p id="long"></p>
在这里点击地图不止一个的时候,有地方标记的数量会出现。我只想要一个最后点击位置的地标。如何解决这个问题..?提前谢谢。
答案 0 :(得分:2)
您可以保留对标记的引用并继续移动它:
var marker;
function placeMarker(location) {
if (!marker) {
marker = new google.maps.Marker({
position: location,
map: map,
});
} else {
marker.setPosition(location);
}
document.getElementById("latt").innerHTML = location.lat();
document.getElementById("long").innerHTML = location.lng();
}
编辑:纬度没有双t,所以id会更有意义为“lat”。我可以向你保证,如果你拼错了,你的同事会因为你不能正确拼写它而感到恼火:)
答案 1 :(得分:0)
在添加新标记之前删除标记。
var map;
var marker;
function initialize() {
var myCenter = new google.maps.LatLng(13.001294, 77.661736);
var mapProp = {
center: myCenter,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
google.maps.event.addListener(map, 'click', function (event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
// Remove last marker
marker.setMap(null);
marker = new google.maps.Marker({
position: location,
map: map,
});
document.getElementById("latt").innerHTML = location.lat();
document.getElementById("long").innerHTML = location.lng();
}
google.maps.event.addDomListener(window, 'load', initialize);