Skip to content Skip to sidebar Skip to footer

Using Geocoder To Make An Address The Center Of A Google Map

I'm trying to write a program that finds the respective values latLng for an address and then using that for the center of the map. Here is my code so far, however the main problem

Solution 1:

you want to set the bounds on the google map object.

var bounds = new google.maps.LatLngBounds();
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);

more info on LatLngBounds

optionaly you could do map.fitBounds(bounds.getCenter()) if you have more than one latlng in the LatLngBounds

Solution 2:

You want to call setCenter() on the map with the new latlng. I would also create the map before you try to do this.

<scripttype="text/javascript">var geocoder = new google.maps.Geocoder();

  var address = '3410 Dr Martin Luther King Jr Blvd, New Bern, NC, US';

  var mapOptions = { 
          mapTypeId: google.maps.MapTypeId.TERRAIN,
          center: new google.maps.LatLng(54.00, -3.00),
          zoom: 5
  };

   var map = new google.maps.Map(document.getElementById("map"), mapOptions);

   geocoder.geocode({'address': address}, function(results, status) {
          if(status == google.maps.GeocoderStatus.OK) 
          {
               result = results[0].geometry.location;
               console.log(result);

               map.setCenter(result);
           }
   });
   </script>

Post a Comment for "Using Geocoder To Make An Address The Center Of A Google Map"