Geocode
Allow the user to click anywhere on the map to display a popup containing the geocoded information for that particular location.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.smartmaps.cloud/packages/smartmaps/smartmaps-gl/v2/umd/smartmaps-gl.min.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
html,
body,
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
const apiKey = "INSERT API-KEY";
const map = new smartmapsgl.Map({
apiKey: apiKey,
container: "map",
center: { lat: 49.02164948779226, lng: 8.439330018049352 },
zoom: 10,
style: smartmapsgl.MapStyle.LIGHT
});
map.on('click', async (event) => {
const coordinates = [event.lngLat.lng, event.lngLat.lat];
const geocodeRequest = {
type: "Feature",
properties: {},
geometry: {
type: "Point",
coordinates: coordinates
},
crs: {
type: "name",
properties: {
name: "urn:ogc:def:crs:OGC:1.3:CRS84"
}
},
searchparams: {
geocodingType: "REVERSE_GEOCODE",
coordFormatOut: "GEODECIMAL_POINT"
},
authentication: {
channel: "Test123"
},
location: {}
};
try {
const response = await fetch(`https://www.yellowmap.de/api_rst/v2/geojson/geocode?apiKey=${apiKey}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(geocodeRequest)
});
const geocodeData = await response.json();
const geocodeProperties = geocodeData.features[0].properties;
const popupContent = `
<strong>Geocoded Data:</strong><br>
City: ${geocodeProperties.city}<br>
City Part: ${geocodeProperties.cityPart}<br>
District: ${geocodeProperties.district}<br>
Country: ${geocodeProperties.country}<br>
Street: ${geocodeProperties.street}<br>
ZIP: ${geocodeProperties.zip}<br>
`;
new smartmapsgl.Popup()
.setLngLat(event.lngLat)
.setHTML(popupContent)
.addTo(map);
} catch (error) {
console.error('Error during geocoding:', error);
}
});
</script>
</body>
</html>