Question

I'm implementing Google Maps into a new project and one page should return a large (100% * 100%) map of Canada. I'm also using Geocoding to determine the latlng to be passed to the map.

Here's the code:

var myLatlng = new google.maps.LatLng(37.775, -122.4183333);
        var myOptions ={
            zoom: 5,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.TERRAIN
        }

        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        var address = "Canada";
        var geocoder = new google.maps.Geocoder(address);
        geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                //map.setCenter(results[0].geometry.location);
                            //The above was too far north
                map.fitBounds(results[0].geometry.viewport);
                map.setZoom(5);
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });

It's working nicely except it's "a little too far to the left". Essentially, it's cut off most of the Maritime provinces. An example can be seen here:

http://50.28.69.176/~sequoia/locations.php

Anyone know how to finesse this so that the country is better centered in the viewport?

Thanks for any help.

Was it helpful?

Solution

Instead of geocoding every time the page is loaded, I'd suggest just getting the correct LatLng that you want, and storing it.

If you still want to stick with this approach, you can use the getCenter() method on a LatLngBounds to get its center.

That way, you can call

map.fitBounds(results[0].geometry.viewport.getCenter())
map.setZoom(5)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top