Monday, May 20, 2024
93
rated 0 times [  99] [ 6]  / answers: 1 / hits: 55469  / 13 Years ago, thu, may 26, 2011, 12:00:00

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.



More From » google-maps-api-3

 Answers
4

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.


[#92033] Wednesday, May 25, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gavenmekhio

Total Points: 732
Total Questions: 89
Total Answers: 93

Location: Central African Republic
Member since Mon, Aug 10, 2020
4 Years ago
;