Skip to content Skip to sidebar Skip to footer

Google Maps V3 Geocode + Zoom

I was using geocode service of Google Maps Version 2 the Javascript API. https://developers.google.com/maps/documentation/javascript/v2/reference However google decided not to supp

Solution 1:

To zoom the map to best show the results of the geocoding operation, you can use the google.maps.Map fitBounds method with the viewport property of the result:

functioncodeAddress() {
    var address = document.getElementById("address").value;
    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
            });
        if (results[0].geometry.viewport) 
          map.fitBounds(results[0].geometry.viewport);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

code snippet:

var geocoder, map, marker;

functioncodeAddress() {
  var address = document.getElementById("address").value;
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      if (marker && marker.setMap) marker.setMap(null);
      marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });
      if (results[0].geometry.viewport)
        map.fitBounds(results[0].geometry.viewport);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });
}

functioninitialize() {
  geocoder = new google.maps.Geocoder();
  map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  google.maps.event.addDomListener(document.getElementById('btn'), 'click', codeAddress);
  codeAddress();

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<scriptsrc="https://maps.googleapis.com/maps/api/js"></script><inputid="address"value="Palo Alto, CA" /><inputid="btn"value="Geocode"type="button" /><divid="map_canvas"></div>

Solution 2:

var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': zipcode }, function(results, status)
{
    if (status == google.maps.GeocoderStatus.OK)
    {
        map.setCenter(results[0].geometry.location);
        map.setZoom(12);
    }
    else
    {
       alert(zipcode + " not found");
       console.log("status : ", status);
    }
});

Post a Comment for "Google Maps V3 Geocode + Zoom"