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?
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?
Share Improve this question edited Nov 27, 2019 at 7:47 ffflabs 17.5k5 gold badges56 silver badges79 bronze badges asked Sep 24, 2013 at 0:30 RobViousRobVious 12.9k25 gold badges105 silver badges185 bronze badges 1- possible duplicate of Get LatLng from Zip Code - Google Maps API. The magic word you are looking for is "Geocoding" (the process of converting addresses into geographic coordinates) – geocodezip Commented Sep 24, 2013 at 0:42
2 Answers
Reset to default 3You 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.
maybe you can do this by php with the following script:
function getLnt($zip){
$url = "http://maps.googleapis./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 ;-)