Well, this is one of those examples that shows it pays off to sleep a night over certain problems.
Yesterday afternoon I scratched my head over the Google Maps V3 API’s behaviour. All I wanted to do is change the zoom level of a map using the fitBounds() method. The latitude and longitude values were coming from a jQuery Ajax request that returned an JSON object. The object looked something like this:
{ "bounds": { "sw":"-45.99579575,170.05493469", "ne":"-45.48679779,170.77724915" } }
I tried the following script to set the new bounds:
var obj = jQuery.parseJSON(ajaxResponse); sw = new google.maps.LatLng(obj.bounds.sw); ne = new google.maps.LatLng(obj.bounds.ne); newbounds = new google.maps.LatLngBounds(sw,ne);
Now, the result was that it completely caked the Map. The map literally zoomed (or panned, who knows?) to uncharted territory after which any interactions with it would not result in any updates. The map had effectively crashed.
WTF, why? I asked myself. So I checked what values google.maps.LatLng were producing. NaN. Not numbers obviously, but why? I chewed on that for half an hour before I decided to leave it for the day.
Now this morning I had a look at it again and it quickly dawned on me… the JSON data was delivered as a string but the google.map.LatLng class expects floats. So I altered the script accordingly:
var obj = jQuery.parseJSON(ajaxResponse); var sw=obj.bounds.sw.split(','); // split string to allow parseFloat of data var ne=obj.bounds.ne.split(','); sw = new google.maps.LatLng(parseFloat(sw[0]),parseFloat(sw[1])); ne = new google.maps.LatLng(parseFloat(ne[0]),parseFloat(ne[1])); newbounds = new google.maps.LatLngBounds(sw,ne); map.fitBounds(newbounds);
And lo and behold… it works.
Dear Uncle Tomm ,
i was knocking my head (and the one of my co-worker) on the wall, and your post solved the problem.
Thank you.