Skip to content

Instantly share code, notes, and snippets.

@wescpy
Created May 9, 2024 03:37
Show Gist options
  • Save wescpy/d6e25e37d732997cfdba6f0fbe9db6a5 to your computer and use it in GitHub Desktop.
Save wescpy/d6e25e37d732997cfdba6f0fbe9db6a5 to your computer and use it in GitHub Desktop.
Vue.js sample calling Google Maps APIs (Geocoding API)
<!DOCTYPE html>
<html>
<head>
<title>Geocoding with Vue</title>
<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="address" placeholder="Enter address">
<button @click="geocodeAddress">Geocode</button>
<p v-if="coordinates">
Coordinates: {{ coordinates.lat }}, {{ coordinates.lng }}
</p>
<p v-if="error">{{ error }}</p>
</div>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
address: '',
coordinates: null,
error: null
};
},
methods: {
async geocodeAddress() {
this.error = null; // Clear previous error
const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${this.address}&key=YOUR_GOOGLE_MAPS_API_KEY`;
try {
const response = await axios.get(url);
const results = response.data.results;
if (results.length > 0) {
this.coordinates = results[0].geometry.location;
} else {
this.error = "No results found";
}
} catch (err) {
this.error = "An error occurred";
console.error(err); // Log error for debugging
}
}
}
}).mount('#app');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment