Question

I've been looking through the docs and all over the web for an example of this and I can't find an example of this use-case.

Given a zip code, I need a rough approximation of the user's location in the form of lat/long coordinates. All I have is the zip code, nothing else.

Can this be done using Google Maps API? If not, what other resources would you suggest looking at?

Was it helpful?

Solution

You can pass any text as the address key for the geocoder. If the geocoding is successsful, you should get an array of results.

From then on you can pick the first result or iterate over the array. Each of its elements should contain an address object, and postal code is one posible field on that obj.

Keep in mind that usps zipcodes are not points nor shapes. They are arrays of points, and the centroid of the polygon drawn by using those points as vertexes probably doesn't have any special meaning.

OTHER TIPS

maybe you can do this by php with the following script:

function getLnt($zip){
  $url = "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($zip)."&sensor=false";

  $result_string = file_get_contents($url);
  $result = json_decode($result_string, true);

  $result1[]=$result['results'][0];
  $result2[]=$result1[0]['geometry'];
  $result3[]=$result2[0]['location'];
  return $result3[0];
}

if you call this function by (* I filtered out the space between chars, it isn't necessary):

 $coords = str_replace(' ','',$foo->zipcode);*
 $val = getLnt($coords);

 /* print latitude & longitude for example */
 print $val['lat'];
 print $val['lng'];

Then after that u can mix it with your google map script like:

function initialize(){
  var myLatlng = new google.maps.LatLng(<?= $val['lat'] ?>,<?= $val['lng'] ?>);
  var mapOptions = {
    zoom: 14,
    center: myLatlng,
    disableDefaultUI: true,
    scrollwheel: false,
  }
  var map = new google.maps.Map(document.getElementById('propMap'), mapOptions);

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'title of location',
      icon: iconBase + 'google-marker.png'
  });
}

Note: This worked fine for me, but maybe there are better ways to do this ;-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top