I have attempted to use Google Maps to add locations to events that the user can create. As such there is an "add location" checkbox that has onclick="initialize()"
, the map and a search box then appear with the search button having onclick="codeAddress()"
. However the initialized map is set at zoom level 10 (as it's London as a whole) yet when someone enters an address for example, I need it to zoom to an appropriate level.
I feel as if this should be simpler that it seems. I've read alot about using LatLngBounds()
but the examples are for more than one marker and you have to set SW and NE corners which im not sure how to calculate appropriately for different searches.
var geocoder;
var map;
var markersArray = [];
function initialize() {
var locationStart = new google.maps.LatLng(51.5073346, -0.12768310000001293);
geocoder = new google.maps.Geocoder();
var myOptions = {
center: locationStart,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: locationStart,
map: map
});
markersArray.push(marker);
}
// Function to remove markers
function clearOverlays() {
if(markersArray) {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
}
}
// Function to search addresses and generate a list of the other options returned
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode({
'address': address,
'region' : 'uk'
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var divTest = document.getElementById("results");
divTest.innerHTML = "";
if (results.length > 1) {
$('#addressOptions').show();
for (var i=0; i<results.length; i++) {
divTest.innerHTML += "<tr><td id=\"address"+ i + "\" onclick=\"grabLocation(" + i + ")\" >" + results[i].formatted_address + "</td></tr>";
};
} else {
$('#addressOptions').hide();
}
divTest.innerHTML += "";
var marker = new google.maps.Marker({
'map' : map,
'position' : results[0].geometry.location,
'preserveViewport' : false
});
map.setCenter(results[0].geometry.location);
markersArray.push(marker);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Apologies if this is a simple question, I've been looking around for a simple answer for a while now.