45 lines
1.3 KiB
JavaScript
45 lines
1.3 KiB
JavaScript
import {ref} from "vue";
|
|
import axios from "axios";
|
|
|
|
export const useGeocode = () => {
|
|
|
|
const center = ref({lat: 50.1314, lng: 14.5256});
|
|
|
|
|
|
const searchGeocode = (address) => {
|
|
return axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURI(address)}&key=${process.env.GOOGLE_MAPS_API_KEY}`).then(response => {
|
|
if (response.data.status !== 'OK') {
|
|
return null;
|
|
}
|
|
|
|
return response.data.results;
|
|
});
|
|
}
|
|
|
|
const searchPlaceName = (lat, lng) => {
|
|
return axios.get(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${process.env.GOOGLE_MAPS_API_KEY}`).then(response => {
|
|
if (response.data.status !== 'OK' || !response.data.results?.length) {
|
|
return null;
|
|
}
|
|
|
|
const results = response.data.results;
|
|
const components = {};
|
|
for (const addressComponent of results[0].address_components) {
|
|
for (const namePartType of ["locality", "postal_town", 'administrative_area_level_2']) {
|
|
if (addressComponent.types.includes(namePartType)) {
|
|
components[namePartType] = addressComponent.long_name
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!Object.keys(components).length) {
|
|
return "Bod na mapě";
|
|
}
|
|
|
|
return Object.values(components).join(", ");
|
|
});
|
|
}
|
|
|
|
return {center, searchGeocode, searchPlaceName}
|
|
}
|