Zum Inhalt

Forward-Geocoding auf Basis mehrerer Felder

Dieses Beispiel zeigt einen mehrfeldigen Geocoding-Prozess, bei dem der Benutzer Adressbestandteile in separate Felder eingibt, etwa Straße und Hausnummer, Stadt, Postleitzahl und Land. Die angegebenen Adressinformationen werden anschließend in geografische Koordinaten (Latitude und Longitude) umgewandelt, die mithilfe eines Markers auf der Karte angezeigt werden.

<!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;
                font-family: Arial, sans-serif;
            }

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

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

            input {
                width: 200px;
                padding: 5px;
                margin-bottom: 5px;
            }

            #submit-button {
                padding: 5px 10px;
                margin-top: 5px;
                width: 100%;
            }
        </style>
    </head>

    <body>
        <div id="input-container">
            <input type="text" id="street-input" placeholder="Street and House Number">
            <input type="text" id="city-input" placeholder="City">
            <input type="text" id="zip-input" placeholder="Postal Code">
            <input type="text" id="country-input" placeholder="Country">
            <button id="submit-button">Geocode</button>
        </div>
        <div id="map"></div>

        <script>
            const apiKey = "[INSERT API-KEY]";

            // Initialize the map
            const map = new smartmapsgl.Map({
                apiKey: apiKey,
                container: "map",
                center: { lat: 49.02164948779226, lng: 8.439330018049352 },
                zoom: 14,
                style: smartmapsgl.MapStyle.LIGHT
            });

            // Variable to store the current marker
            let currentMarker = null;

            document.getElementById('submit-button').addEventListener('click', async () => {
                const street = document.getElementById('street-input').value;
                const city = document.getElementById('city-input').value;
                const zip = document.getElementById('zip-input').value;
                const country = document.getElementById('country-input').value;

                if (!street && !city && !zip && !country) {
                    alert("Please enter at least one search criteria.");
                    return;
                }

                // Prepare the geocode request
                const geocodeRequest = {
                    type: "Feature",
                    properties: {},
                    geometry: {
                        type: "Point",
                        coordinates: [0, 0] // Dummy coordinates
                    },
                    crs: {
                        type: "name",
                        properties: {
                            name: "urn:ogc:def:crs:OGC:1.3:CRS84"
                        }
                    },
                    searchparams: {
                        geocodingType: "GEOCODE",
                        coordFormatOut: "GEODECIMAL_POINT"
                    },
                    authentication: {
                        channel: "Test123"
                    },
                    location: {
                        street: street,
                        city: city,
                        zip: zip,
                        country: country
                    }
                };

                try {
                    // Send the geocode request
                    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();

                    if (geocodeData.features && geocodeData.features.length > 0) {
                        const coordinates = geocodeData.features[0].geometry.coordinates;

                        // Center the map on the new coordinates
                        map.setCenter({ lat: coordinates[1], lng: coordinates[0] });

                        // Remove the old marker if it exists
                        if (currentMarker) {
                            currentMarker.remove();
                        }

                        // Add the new marker
                        currentMarker = new smartmapsgl.Marker()
                            .setLngLat([coordinates[0], coordinates[1]])
                            .addTo(map);
                    } else {
                        alert("No results found.");
                    }
                } catch (error) {
                    console.error('Error during geocoding:', error);
                    alert("An error occurred while geocoding.");
                }
            });
        </script>
    </body>

</html>