可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am trying to update the location of a marker with out refreshing the whole page. I have tried to use setTimeout(function()
however I am having no luck..
here is my code I have so far..
thanks in advance
function initialize() { var mapOptions = { center: new google.maps.LatLng(35.66, -80.50), zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); var json = (function () { var json = null; $.ajax({ 'async': false, 'global': false, 'url': "getjson.php", 'dataType': "json", 'success': function (data) { json = data; } }); return json;})(); for (var i = 0, length = json.length; i
here is my JSON output.
[{"lat":35.6606376,"lng":-80.5048653,"content":"bca"}, {"lat":42.6799504,"lng":-36.4949205,"content":"abc"}]
回答1:
I would suggest using setInterval rather than setTimeout.
Here is some code that simulates an update via JSON in a fiddle, using your provided JSON with the required "description" member added for each marker:
var map = null; var gmarkers = []; var intervalNumber = 0; setInterval(function () { new Request.JSON({ url: '/echo/json/', data: { json: JSON.encode([{ "lat": 35.6606376 + (0.01 * intervalNumber), "lng": -80.5048653 + (0.1 * intervalNumber), "content": "bca", "description":"first marker" }, { "lat": 42.6799504 + (0.01 * intervalNumber), "lng": -36.4949205 - (0.1 * intervalNumber), "content": "abc", "description": "second marker" }]), delay: 3 }, onSuccess: function (response) { update_map(response); intervalNumber++; } }).send(); }, 5000); update_map = function (data) { var bounds = new google.maps.LatLngBounds(); // delete all existing markers first for (var i = 0; i "+marker.getPosition().toUrlValue(6)); infoWindow.open(map, marker); }); (function (marker, data) { google.maps.event.addListener(marker, "click", function (e) { infoWindow.setContent(data.description+"
"+marker.getPosition().toUrlValue(6)); infoWindow.open(map, marker); }); })(marker, data[i]); gmarkers.push(marker); } // zoom the map to show all the markers, may not be desirable. map.fitBounds(bounds); }; function initialize() { // initialize the map on page load. var mapOptions = { center: new google.maps.LatLng(35.66, -80.50), zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); // add the markers to the map if they have been loaded already. if (gmarkers.length > 0) { for (var i = 0; i
回答2:
https://developers.google.com/maps/documentation/javascript/reference
markerObject.setPosition(latlng:LatLng|LatLngLiteral)
I don't think you need to redraw the map, but in case you do:
google.maps.event.trigger(mapObject, 'resize');