Google Map V3 not centering, displays only part of map

mpemburn picture mpemburn · Oct 23, 2010 · Viewed 9.7k times · Source

I'm developing a jQTouch-based app for the iPhone and part of it uses the Google Maps API (V3). I want to be able to pass the geolocation coordinates to the map and have it center the location with a marker. What I'm getting now is the map at the proper zoom level but the desired center-point appears in the upper-righthand corner. It's also showing only about a third of the map area (the rest is gray) and it behaves somewhat erratically when you pan or zoom. Here's the code:


var coords = { latitude : "35.510630", longitude : "-79.255374" };
var latlng = new google.maps.LatLng(coords.latitude, coords.longitude);
var myOptions = {
    zoom: 12,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map($("#map_canvas").get(0), myOptions);
var marker = new google.maps.Marker({
    position: latlng, 
    map: map, 
});     

BTW: It looks and behaves the same on other platforms/browsers as well.

Thoughts?

Thanks in advance,

Mark


Added Here's a link that'll show exactly what's happening: Screen shot of iPhone emulator

Answer

Brett DeWoody picture Brett DeWoody · Mar 24, 2011

I'm guessing you're using AJAX to display the map, or have the map hidden at some point and then display it based on an action?

In this case Google doesn't know the size of the map container and it will draw only part of the map, usually off-centered.

To fix this, resize the map, then re-center on your lat/lng. Something like this:

google.maps.event.trigger(map, 'resize');

// Recenter the map now that it's been redrawn               
var reCenter = new google.maps.LatLng(yourLat, yourLng);
map.setCenter(reCenter);