Alexander Solonik Alexander Solonik - 3 months ago 10
Javascript Question

Google marker disappearing when use setPosition to change position

I have a simple google maps , and I am creating a simple map with a marker with the below code:

var mapElement = document.getElementById('hr-map');
// Create the Google Map using our element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);
// Let's also add a marker while we're at it
var marker = new google.maps.Marker({
position: new google.maps.LatLng(25.098353, 55.156124),
map: map,
title: 'HR',
scrollwheel: false,
icon: 'images/res/map-marker.png'
});


Now all I wanted to do is move the marker from the center of the map to somewhere below the center, I googled and check the below two links, one is a SO question and the fiddle demonstrating changing the marker position.

FIDDLE HERE

SO THREAD

Now I used the same line of code used in the fiddle and also in the SO thread and wrote the below line of code:

marker.setPosition(google.maps.LatLng(25.098353, 55.156124));


But adding the above line of code actually makes the entire marker disappear. So now my code looks line below:

var mapElement = document.getElementById('dynamic-hr-map');
// Create the Google Map using our element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);
// Let's also add a marker while we're at it
var marker = new google.maps.Marker({
position: new google.maps.LatLng(25.098353, 55.156124),
map: map,
title: 'Dynamic HR',
scrollwheel: false,
icon: 'images/res/map-marker.png'
});

marker.setPosition(google.maps.LatLng(25.098353, 55.156124));


So well why is my marker disappearing in the first place ? Is there any solution to this ?

Answer

You are missing the new keyword. You need to create a new instance of LatLng object before using it.

    marker.setPosition(new google.maps.LatLng(25.098353, 55.156124)); 
Comments