Search code examples
javascriptleafletopenstreetmap

How can I color a city in open street map based on longitude and latitude?


I am using open street map to show map in my application. The following code is used to show the open street map.

 <div id="map" style="width: 90%; height: 420px"></div>

I am using the leaflet library to show the map.

         function drawMap() {
            var mapOptions = {
                center: [23.8103, 90.4125],
                zoom: 7
            };
            var map = new L.map('map', mapOptions);
            var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
            map.addLayer(layer);
        }

However, the map is showed but I want to color a city on this map based on longitude and latitude. I have searched a lot and found some links. Geofencing Bit I have not got any clue to implement this. How can I color a city on the map based on latitude and longitude?

I am using flask as a backend.


Solution

  • Use https://nominatim.openstreetmap.org/ to get the polygon coordinates, however this API accepts the name of the city so you need to use reverse gocoding to convert coordinates into city name. You can do that with esri-leaflet-geocoder.

     const geocoder = L.Control.Geocoder.nominatim();
    
      const geocodeService = L.esri.Geocoding.geocodeService();
      const yourCoordinates = [23.8103, 90.4125];
    
      geocodeService
        .reverse()
        .latlng(yourCoordinates)
        .language("eng")
        .run(function(error, result) {
          if (error) {
            return;
          }
    
          if (result && result.address) {
            fetch(
              `https://nominatim.openstreetmap.org/search.php?q=${
                result.address.City
              }&polygon_geojson=1&format=json`
            )
              .then(res => res.json())
              .then(res => {
                console.log(res[1].geojson);
                L.geoJSON(res[1].geojson).addTo(map);
              });
          }
        });
    

    Demo