Using Google Maps API v3, is there a way to set the center of the map on initialize? I have a workaround using this code:
var geocoder; var map; function initialize() { geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(-34.397, 150.644); var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); codeAddress('germany'); } function codeAddress(address) { geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); } }); }
The only problem is that when it initializes, it centers it to the "latlng" for a split second. I'm can't figure out how to set the center in "myOptions". I though I could return "results[0].geometry.location" from the codeAddress function and pass it to myOptions, but that doesn't work.
Thanks for any help.
Update Since I can't remove "center" altogether, I'm wondering if there's a way to pass the address to the options.
From Google API:
To initialize a Map, we first create a Map options object to contain map initialization variables. This object is not constructed; instead it is created as an object literal. There are two required options for every map: center and zoom.
Go to the directions, map, or Street View image you want to share. Select Share or embed map. If you don't see this option, click Link to this map. Optional: To create a shorter web page link, check the box next to "Short URL."
Well a simple solution could be to initialize the map in your codeAddress function:
var geocoder, map; function codeAddress(address) { geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'address': address }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var myOptions = { zoom: 8, center: results[0].geometry.location, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); } }); }
This should solve the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With