Last active
April 20, 2018 15:45
-
-
Save atillay/70b2ab3a3a6ee64dfa386e61fbcf2735 to your computer and use it in GitHub Desktop.
Google Maps API address components parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* parseGoogleMapsAddressComponents | |
* | |
* Converts the addressComponents sent by GoogleMaps into a clean object | |
* The precision value allows to know what is the precision level of the address (one point per component) | |
* Ex: If the street number is available, then the precision value would be 6. | |
* | |
* @param addressComponents | |
* @returns object | |
*/ | |
function parseGoogleMapsAddressComponents(addressComponents) { | |
var address = { | |
country: null, | |
region: null, | |
department: null, | |
city: null, | |
street: null, | |
streetNumber: null | |
}; | |
addressComponents.forEach(function(addressComponent) { | |
var countryIdx = addressComponent.types.indexOf('country'), | |
regionIdx = addressComponent.types.indexOf('administrative_area_level_1'), | |
departmentIdx = addressComponent.types.indexOf('administrative_area_level_2'), | |
cityIdx = addressComponent.types.indexOf('locality'), | |
streetIdx = addressComponent.types.indexOf('route'), | |
streetNumberIdx = addressComponent.types.indexOf('street_number'); | |
switch (true) { | |
case countryIdx !== -1 : | |
address.country = addressComponent.long_name; | |
break; | |
case regionIdx !== -1 : | |
address.region = addressComponent.long_name; | |
break; | |
case departmentIdx !== -1 : | |
address.department = addressComponent.long_name; | |
break; | |
case cityIdx !== -1 : | |
address.city = addressComponent.long_name; | |
break; | |
case streetIdx !== -1 : | |
address.street = addressComponent.long_name; | |
break; | |
case streetNumberIdx !== -1 : | |
address.streetNumber = addressComponent.long_name; | |
break; | |
} | |
}); | |
var precision = 0; | |
for(var key in address) { | |
if (address[key] !== null) { | |
precision++; | |
} | |
} | |
address.precision = precision; | |
return address; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment