Reputation: 1
I just want to move the marker on the map, and have declared the variable map
, marker
as global, but I'm not able to use it in the function moveMarker()
. I'm new to JavaScript, so this problem may be simple but I still can't solve it - can anybody help me to fix it?
var map;
var marker;
function initialize() {
var myLatLng = new google.maps.LatLng(50, 50),
myOptions = {
zoom: 4,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
marker = new google.maps.Marker({
position: myLatLng,
map: map,
draggable: true
});
marker.setMap(map);
setTimeout("moveMarker(1)", 2000);
}
function moveMarker(i) {
//delayed so you can see it move
if (i > 10) {
return;
}
var myLatLng = new google.maps.LatLng(50 + 0.1 * i, 50 + 0.1 * i);
marker.setPosition(myLatLng);
map.panTo(myLatLng);
var latlng = marker.getPosition();
newlatlng = latlng.toString();
marker.setTitle(newlatlng);
setTimeout("moveMarker(" + (i + 1) + ")", 1500);
}
window.onload = function () {
// Setup the dnd listeners.
initialize();
};
Upvotes: 0
Views: 3285
Reputation: 56509
The problem is not in Google Map's PanTo
method. The reason for the problem is your myLatLng
variable.
So change the scope of to myLatLng
variable to Global
, problem will be solved.
Check this JSFIddle
Upvotes: 0
Reputation: 1907
You need to do replace your "," with ";", otherwise it thinks you are re-defining variable "map":
var map;
var marker;
function initialize() {
var myLatLng = new google.maps.LatLng(50, 50);
myOptions = {
zoom: 4,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
marker = new google.maps.Marker({
position: myLatLng,
map: map,
draggable: true
});
marker.setMap(map);
setTimeout("moveMarker(1)", 2000);
}
function moveMarker(i) {
//delayed so you can see it move
if (i > 10) {
return;
}
var myLatLng = new google.maps.LatLng(50 + 0.1 * i, 50 + 0.1 * i);
marker.setPosition(myLatLng);
map.panTo(myLatLng);
var latlng = marker.getPosition();
newlatlng = latlng.toString();
marker.setTitle(newlatlng);
setTimeout("moveMarker(" + (i + 1) + ")", 1500);
}
window.onload = function () {
// Setup the dnd listeners.
initialize();
};
Upvotes: 2