'Google Maps API zoom after setcenter

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.



Solution 1:[1]

The geocoder returns a suggested viewport

results[0].geometry.viewport

It can be used to zoom to a level that makes sense for the result returned

Example

code snippet:

// modified from http://www.weltmeer.ch/divelog/
// globals
var map = null;
var geocoder = null;

function initialize() {
  geocoder = new google.maps.Geocoder();
  var myOptions = {
    zoom: 2,
    center: new google.maps.LatLng(47.288828765662416, 7.945261001586914),
    mapTypeControl: true,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
    },
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  findAddress("United States");
}

function findAddress(address) {
  var addressStr = document.getElementById("stateselect").value;
  if (!address && (addressStr != ''))
    address = "State of " + addressStr;
  else
    address = addressStr;
  if ((address != '') && geocoder) {
    geocoder.geocode({
      'address': address
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          if (results && results[0] &&
            results[0].geometry && results[0].geometry.viewport)
            map.fitBounds(results[0].geometry.viewport);
        } else {
          alert("No results found");
        }
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
}
html,
body {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

#map_canvas {
  height: 90%;
}

#TOPNAV {
  height: 10%;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>

<head>
  <title>Zoom to State with Select List (Google Maps API)</title>
  <script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
  </script>
</head>

<body onload="initialize()">
  <div id="TOPNAV">
    <select id="stateselect" name="countryselect" class="textfeld" onclick="findAddress();return false" onchange="findAddress();return false" onfocus="">
      <option value=''>Select a State....</option>
      <option value="Alabama">Alabama</option>
      <option value="Alaska">Alaska</option>
      <option value="Arizona">Arizona</option>
      <option value="Arkansas">Arkansas</option>
      <option value="California">California</option>
      <option value="Colorado">Colorado</option>
      <option value="Connecticut">Connecticut</option>
      <option value="Delaware">Delaware</option>
      <option value="Florida">Florida</option>
      <option value="Georgia">Georgia</option>
      <option value="Hawaii">Hawaii</option>
      <option value="Idaho">Idaho</option>
      <option value="Illinois">Illinois</option>
      <option value="Indiana">Indiana</option>
      <option value="Iowa">Iowa</option>
      <option value="Kansas">Kansas</option>
      <option value="Kentucky">Kentucky</option>
      <option value="Louisiana">Louisiana</option>
      <option value="Maine">Maine</option>
      <option value="Maryland">Maryland</option>
      <option value="Massachusetts">Massachusetts</option>
      <option value="Michigan">Michigan</option>
      <option value="Minnesota">Minnesota</option>
      <option value="Mississippi">Mississippi</option>
      <option value="Missouri">Missouri</option>
      <option value="Montana">Montana</option>
      <option value="Nebraska">Nebraska</option>
      <option value="Nevada">Nevada</option>
      <option value="New Hampshire">New Hampshire</option>
      <option value="New Jersey">New Jersey</option>
      <option value="New Mexico">New Mexico</option>
      <option value="New York">New York</option>
      <option value="North Carolina">North Carolina</option>
      <option value="North Dakota">North Dakota</option>
      <option value="Ohio">Ohio</option>
      <option value="Oklahoma">Oklahoma</option>
      <option value="Oregon">Oregon</option>
      <option value="Pennsylvania">Pennsylvania</option>
      <option value="Rhode Island">Rhode Island</option>
      <option value="South Carolina">South Carolina</option>
      <option value="South Dakota">South Dakota</option>
      <option value="Tennessee">Tennessee</option>
      <option value="Texas">Texas</option>
      <option value="Utah">Utah</option>
      <option value="Vermont">Vermont</option>
      <option value="Virginia">Virginia</option>
      <option value="Washington">Washington</option>
      <option value="West Virginia">West Virginia</option>
      <option value="Wisconsin">Wisconsin</option>
      <option value="Wyoming">Wyoming</option>
    </select>
  </div>
  <div id="map_canvas"></div>
</body>

</html>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1