Google Maps API v3 - Get map by address ?

Rafael Herscovici picture Rafael Herscovici · Jul 30, 2011 · Viewed 94.4k times · Source

i am new to google maps, and i would like to integrate it into my website ( Yellow pages kind of site ).

i currently have the following code:

<!DOCTYPE html>

<html>
<head>
    <title></title>
    <script type="text/javascript" src="jquery-1.6.2.min.js"></script>
    <script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var latlng = new google.maps.LatLng(-34.397, 150.644);
            var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
        }); 
    </script>
</head>
<body>
    <div id="map_canvas" style="width: 500px; height: 300px; position: relative; background-color: rgb(229, 227, 223);"></div>
</body>
</html>

This code does work, and showing me the map for the specific Lat/Long

but, i want to be able to specifiy an address and not lat/long params, since i do have the addresses of the companies in the phonebook, but do not have the lat/long values.

i tried searching for this, but i only found something similar on the V2 version, which was deprecated.

Answer

Howard picture Howard · Jul 30, 2011

What you are looking for is Geocode feature in google service; first give an address to get a LatLng, then call setCenter to pan the map to the specific location. Google's API wrapped it very good and you can see how it works through this example:

var geocoder;
var map;
function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var mapOptions = {
    zoom: 8,
    center: latlng
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function codeAddress() {
  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
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);