Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

jquery - Google Maps api V3 update marker

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.

Nothing happens when I click on the updatemap button.

Here's my code so far:

$(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);

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update

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);

This should be just

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

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...