Zum Inhalt

Reverse-Geocoding auf Basis des Standorts des Nutzers

Dieses Beispiel zeigt, wie Reverse-Geocoding unter Verwendung des aktuellen Standorts des Nutzers funktioniert. Die geocodierte Adresse wird anschließend in der Box in der oberen linken Ecke der Karte angezeigt.

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Reverse Geocoding with User Location</title>
        <script src="https://cdn.smartmaps.cloud/packages/smartmaps/smartmaps-gl/v2/umd/smartmaps-gl.min.js"></script>

        <style>
            body {
                margin: 0;
                padding: 0;
                font-family: Arial, sans-serif;
            }

            html, body, #map {
                height: 100%;
            }

            #input-container {
                position: absolute;
                top: 10px;
                left: 10px;
                z-index: 1;
                background-color: white;
                padding: 10px;
                border-radius: 5px;
                box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
            }

            #address-input {
                width: 300px;
                padding: 5px;
            }
        </style>
    </head>

    <body>
        <div id="input-container">
            <input type="text" id="address-input" placeholder="Your location will appear here" readonly>
        </div>
        <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
            });

            // Add geolocate control to the map
            const geolocate = new smartmapsgl.GeolocateControl({
                positionOptions: {
                    enableHighAccuracy: true
                },
                trackUserLocation: false
            });

            map.addControl(geolocate);

            // Trigger geolocation on map load
            map.on('load', () => {
                geolocate.trigger();
            });

            // Listen for the geolocate event
            geolocate.on('geolocate', async (e) => {
                const lon = e.coords.longitude;
                const lat = e.coords.latitude;

                // Perform reverse geocoding
                const geocodeRequest = {
                    type: "Feature",
                    properties: {},
                    geometry: {
                        type: "Point",
                        coordinates: [lon, lat]
                    },
                    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=${smartmapsgl.encodeString(apiKey)}`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(geocodeRequest)
                    });

                    const geocodeData = await response.json();
                    const geocodeProperties = geocodeData.features[0].properties;

                    // Format the address
                    const formattedAddress = `${geocodeProperties.street} ${geocodeProperties.houseNo}, ${geocodeProperties.zip} ${geocodeProperties.city}, ${geocodeProperties.isoCountry}`;

                    // Update the input field
                    document.getElementById('address-input').value = formattedAddress;
                } catch (error) {
                    console.error('Error during reverse geocoding:', error);
                }
            });
        </script>
    </body>

</html>