Advertisement
Guest User

geocode

a guest
Feb 27th, 2025
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 5.91 KB | Source Code | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>Structured Geocoding with TomTom API</title>
  7.  
  8.     <!-- Include Leaflet.js -->
  9.     <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
  10.     <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
  11.  
  12.     <style>
  13.         #map {
  14.             width: 100%;
  15.             height: 500px;
  16.         }
  17.         body {
  18.             font-family: Arial, sans-serif;
  19.             margin: 0;
  20.             padding: 0;
  21.         }
  22.         #search-container {
  23.             margin: 10px;
  24.             padding: 10px;
  25.             background: #f9f9f9;
  26.             border: 1px solid #ccc;
  27.         }
  28.         #search-box {
  29.             width: 300px;
  30.             padding: 5px;
  31.         }
  32.         #search-button {
  33.             padding: 5px 10px;
  34.         }
  35.     </style>
  36. </head>
  37. <body>
  38.     <h1 style="text-align: center;">Structured Geocoding with TomTom API</h1>
  39.     <div id="search-container">
  40.         <input type="text" id="search-box" placeholder="Enter query (e.g., 'ketintang surabaya jawa timur')" />
  41.         <button id="search-button">Search</button>
  42.     </div>
  43.     <div id="map"></div>
  44.  
  45.     <script>
  46.         const apiKey = 'Gixt05RAvLI57chTAGgMFzNaxcYAyigl'; // Your TomTom API Key
  47.  
  48.         // Initialize the map with OpenStreetMap as the base layer
  49.         const map = L.map('map').setView([-7.25, 112.75], 12); // Centered on Surabaya
  50.  
  51.         // Add OpenStreetMap tiles
  52.         L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  53.             attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
  54.         }).addTo(map);
  55.  
  56.         let searchMarkers = []; // To store all search result markers
  57.  
  58.         // Function to handle the search button click
  59.         document.getElementById('search-button').addEventListener('click', async function () {
  60.             const query = document.getElementById('search-box').value.trim();
  61.             if (!query) {
  62.                 alert('Please enter a query in the format: "streetName municipality countrySubdivision".');
  63.                 return;
  64.             }
  65.  
  66.             // Parse the input into streetName, municipality, and countrySubdivision
  67.             const parts = query.split(' ');
  68.             if (parts.length < 3) {
  69.                alert('Please enter a valid query with three parts: "streetName municipality countrySubdivision".');
  70.                return;
  71.            }
  72.  
  73.            const streetName = parts[0];
  74.            const municipality = parts[1];
  75.            const countrySubdivision = parts.slice(2).join(' '); // Handle multi-word subdivisions
  76.  
  77.            try {
  78.                // Fetch structured geocoding results from TomTom API
  79.                const url = `https://api.tomtom.com/search/2/structuredGeocode.json?countryCode=ID&limit=5&streetName=${encodeURIComponent(streetName)}&municipality=${encodeURIComponent(municipality)}&countrySubdivision=${encodeURIComponent(countrySubdivision)}&view=Unified&key=${apiKey}`;
  80.                const response = await fetch(url);
  81.                if (!response.ok) {
  82.                    throw new Error(`Error fetching geocoding data: HTTP ${response.status}`);
  83.                }
  84.  
  85.                const data = await response.json();
  86.                console.log('Geocoding API Response:', data);
  87.  
  88.                // Check if results are available
  89.                if (!data.results || data.results.length === 0) {
  90.                    alert('No results found for the given query.');
  91.                    return;
  92.                }
  93.  
  94.                // Clear previous markers
  95.                searchMarkers.forEach(marker => map.removeLayer(marker));
  96.                 searchMarkers = [];
  97.  
  98.                 // Extract and display all results
  99.                 const results = data.results;
  100.                 const bounds = []; // To store coordinates for fitting the map view
  101.  
  102.                 results.forEach((result, index) => {
  103.                     const position = result.position;
  104.                     const address = result.address.freeformAddress;
  105.  
  106.                     // Generate a random color for the marker
  107.                     const markerColor = getRandomColor();
  108.  
  109.                     // Create a custom icon with the generated color
  110.                     const customIcon = L.divIcon({
  111.                         className: 'custom-icon',
  112.                         html: `<div style="background-color: ${markerColor}; width: 20px; height: 20px; border-radius: 50%; border: 2px solid white;"></div>`,
  113.                         iconSize: [20, 20],
  114.                         iconAnchor: [10, 10]
  115.                     });
  116.  
  117.                     // Add a marker for each result
  118.                     const marker = L.marker([position.lat, position.lon], { icon: customIcon }).addTo(map);
  119.                     marker.bindPopup(`<strong>Result ${index + 1}:</strong><br>${address}`).openPopup();
  120.                     searchMarkers.push(marker);
  121.  
  122.                     // Store the coordinates for fitting the map view
  123.                     bounds.push([position.lat, position.lon]);
  124.                 });
  125.  
  126.                 // Adjust the map view to fit all markers
  127.                 if (bounds.length > 0) {
  128.                     map.fitBounds(bounds);
  129.                 }
  130.             } catch (error) {
  131.                 console.error('Error fetching geocoding data:', error);
  132.                 alert('Failed to fetch geocoding data. Please try again.');
  133.             }
  134.         });
  135.  
  136.         // Function to generate a random color for each marker
  137.         function getRandomColor() {
  138.             const letters = '0123456789ABCDEF';
  139.             let color = '#';
  140.             for (let i = 0; i < 6; i++) {
  141.                color += letters[Math.floor(Math.random() * 16)];
  142.            }
  143.            return color;
  144.        }
  145.    </script>
  146. </body>
  147. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement