如何根据经度和纬度在开放的街道地图中给城市着色?

问题描述 投票:1回答:1

我正在使用开放式街道地图在我的应用程序中显示地图。以下代码用于显示开放的街道地图。

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

我正在使用传单库来显示地图。

         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);
        }

但是,显示了地图,但我想根据经度和纬度在地图上给城市着色。我搜索了很多,发现了一些链接。 Geofencing我没有任何线索来实现这一目标。如何根据经度和纬度在地图上给城市着色?

我正在使用flask作为后端。

javascript leaflet openstreetmap
1个回答
1
投票

使用https://nominatim.openstreetmap.org/获取多边形坐标,但是此API接受城市名称,因此您需要使用反向gocoding将坐标转换为城市名称。您可以使用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

© www.soinside.com 2019 - 2024. All rights reserved.