I created a function to take location input, pass it to Google Maps Javascript API V2, and return a latitude/longitude/normalized address that I'll have to split into different fields in a database (i.e. city, state, postal). I'm requiring at least a level 5/post code accuracy for the input so that the returned data from Google will always have...
- Country
- City (Locality)
- State (Administrative Area)
- Postal
- Lat/Long
Here's some info on the JSON object structure that Google returns.
http://code.google.com/apis/maps/documentation/javascript/v2/services.html#Geocoding_Structured
Problem: For some instances, Placemark.AddressDetails will not include a postal code, while the summarized Placemark.address will include the postal code.
For example, the following input examples will return a postal code inside Placemark.address, but not Placemark.AddressDetails;
- 10437 Innovation Drive, Milwaukee, WI 53226
- MOMA
- Empire State Building --> this actually returns the postal code inside of some weird "DependentLocality" under SubAdministrativeArea.Locality
Here's my troubleshooting code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<!-- You must insert your maps API script here. -->
<script language="javascript" type="text/javascript" src="http://www.json.org/json2.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var geocoder = new GClientGeocoder();
$.geolocateAddress = function(address)
{
geocoder.getLocations(address, function(response)
{
if (response != null && response.Placemark != undefined)
{
var placemark = response.Placemark[0];
// Placemark has Post code or higher accuracy -> http://code.google.com/apis/maps/documentation/javascript/v2/reference.html#GGeoAddressAccuracy
if (placemark.AddressDetails.Accuracy >= 5)
{
alert(placemark.address);
try {
alert(placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber);
} catch (err) {
alert('What the deuce? Why is there no postal code?... I bet you the placemark.address has the postal code.');
alert(JSON.stringify(placemark));
}
} else {
alert('Sorry, this requires at least a postal code input for accuracy')
}
} else {
alert('Failed to geo locate address');
}
});
};
$("#location").blur(function(event)
{
var address = $("#location").val();
$.geolocateAddress(address);
});
});
</script>
<form action="" method="get">
<input title="Location" type="text" value="" id="location" />
</form>
Phew... Is there something I'm just not understanding about schema of Google Maps placemarks? Would I be able to solve this problem by upgrading to Google Maps Javascript API V3? (V2 JSON objects seems more intuitive IMO)
http://code.google.com/apis/maps/documentation/javascript/services.html
I'm about to throw in the towel on this. Hopefully somebody can help!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…