[javascript] Google Maps setCenter()

I'm using google maps. In my code i've used setCenter() function. My problem is that marker is always located on top left corner of map area (not at the center). Please tell me how to resolve it?

My piece of code is

lat = 46.437857;
lon = -113.466797;

marker = new GMarker(new GLatLng(lat, lon));


var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(20, 40));
map.addControl(new GLargeMapControl3D(), topRight);
map.setCenter(new GLatLng(lat, lon), 5);

map.addOverlay(marker);

This question is related to javascript google-maps

The answer is


For me above solutions didn't work then I tried

map.setCenter(new google.maps.LatLng(lat, lng));

and it worked as expected.


@phoenix24 answer actually helped me (whose own asnwer did not solve my problem btw). The correct arguments for setCenter is

map.setCenter({lat:LAT_VALUE, lng:LONG_VALUE});

Google Documentation

By the way if your variable are lat and lng the following code will work

map.setCenter({lat:lat, lng:lng});

This actually solved my very intricate problem so I thought I will post it here.


in your code, at line

map.setCenter(new GLatLng(lat, lon), 5);

the setCenter method takes just one parameter, for the lat:long location. Why are you passing two parameters there ?

I suggest you should change it to,

map.setCenter(new GLatLng(lat, lon));

I searched and searched and finally found that ie needs to know the map size. Set the map size to match the div size.

map = new GMap2(document.getElementById("map_canvas2"), { size: new GSize(850, 600) });

<div id="map_canvas2" style="width: 850px; height: 600px">
</div>