Google Maps api V3 更新标记 [英] Google Maps api V3 update marker

查看:35
本文介绍了Google Maps api V3 更新标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张可以加载的地图.我想添加一个标记,从文本框中获取它的纬度和经度,但我无法理解.

I've got a map that loads. I want to add a marker that gets it's lat and long from text boxes, and I can't fathom it.

当我点击 updatemap 按钮时没有任何反应.

Nothing happens when I click on the updatemap button.

这是我目前的代码:

$(document).ready(function () {
    alert("Dom, dom dom dom dom");


var map;
var marker;

function initialize() {
    var myLatlng = new google.maps.LatLng(40.65, -74);
    var myOptions = {
        zoom: 2,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
    }

    var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
}



$("#updateMap").click(function(){


    var newLatLng = new google.maps.LatLng(lat, lng);
    marker.setPosition(newLatLng);

    var lat = parseFloat(document.getElementById('markerLat').value);
    var lng = parseFloat(document.getElementById('markerLng').value);
    var newLatLng = new google.maps.LatLng(lat, lng);


    marker = new google.maps.Marker({
        position: newLatLng,
        map: map,
        draggable: true
    });


});


});



// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);

});

推荐答案

更新

此外,您的全局 map 引用永远不会设置为实际地图实例,因为您使用本地 var 相同名称对其进行了阴影处理.

Also, your global map reference is never set to the actual map instance since you shadow it with a local var same name.

var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

这应该只是

map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

<小时>

您在初始化之前使用 latlng 作为标记位置(除非它们在某处全局设置):


You're using lat and lng for the marker position before they're initialized (unless they're globally set somewhere):

var newLatLng = new google.maps.LatLng(lat, lng);
marker.setPosition(newLatLng);

如果你想更新同一个标记的位置而不是创建一个新的,你应该这样做:

If you want to update the position of the same marker and not create a new one, you should simply be doing this:

$("#updateMap").click(function(){
    var lat = parseFloat(document.getElementById('markerLat').value);
    var lng = parseFloat(document.getElementById('markerLng').value);
    var newLatLng = new google.maps.LatLng(lat, lng);
    marker.setPosition(newLatLng);
});

这篇关于Google Maps api V3 更新标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆