Custom Search
Logiclabz

Search / Zoom to an address in Google Map using its API

  

The following piece of script would load a google map and then search for particular address using geocoder.geocode method in Google Map API.

   var geocoder;
   var map;
   function initialize() {
        geocoder = new google.maps.Geocoder();
        var myLatlng = new google.maps.LatLng(sLat, sLng);
        var myOptions = {
            zoom: 5,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
	GoToAddress();
   }
   function GoToAddress() {
        var address = "Adyar, Chennai, India"; // Address to Search
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                map.setZoom(15);
            } else {
                alert("Search was not successful for the following reason: " + status);
            }
        });
    }
    window.onload = function () {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "http://maps.google.com/maps/api/js?sensor=false&key=__Your_Google_Map_API_registered_Key__&callback=initialize";
        document.body.appendChild(script);
    };

initialize() method would render google map with your registered google map api key.

GoToAddress() method uses geocoder.geocode in google map api for searching particular location on map. And on google.maps.GeocoderStatus.OK status, it zooms the map with desired zoom level.



  


Leave a reply




Do you like this post?