Skip to content

Instantly share code, notes, and snippets.

@alexfinnarn
Last active February 13, 2018 18:53
Show Gist options
  • Save alexfinnarn/34e8be274b9d61677acc548783f49e30 to your computer and use it in GitHub Desktop.
Save alexfinnarn/34e8be274b9d61677acc548783f49e30 to your computer and use it in GitHub Desktop.
geocodeLocation() function
geocodeLocation(lat, long, that) {
// google object is in global scope loaded by vue-google-maps.
const geocoder = new google.maps.Geocoder;
geocoder.geocode({'location': {'lat': lat, 'lng': long}}, function(results, status) {
if (status === 'OK') {
// Make sure there is at least one result.
if (results[0]) {
// Find locality first and then state.
let placeName = '';
const location = results.find((el) => {
// "locality" is city short_name, e.g. Boulder.
// "administrative_area_level_1" is state short_name, e.g. "CO".
el.address_components.find((comp) => {
if (comp.types.includes('locality')) {
// Since the locality is in the formatted_address field,
// we can use it to truncate string.
placeName = comp.short_name +
el.formatted_address.split(comp.short_name)[1];
}
})
});
// Set the place name to show to user.
if (placeName) {
that.userLocationGuess = placeName;
} else {
// If no placeName, then just list coordinates.
console.log('Failed to generate place name.');
that.userLocationGuess =
`${that.userLocation.latitude},${that.userLocation.longitude}`;
}
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment