使用 JSON 坐标在传单地图上绘制国家边界

Draw country border on leaflet map using JSON coordinates

我有一张传单地图,我在一个很长的 JSON 文件中有一组国家边界。我正在尝试使用 JSON 坐标沿着地图对象中显示的国家/地区的边界绘制实心绿色边框。

我也不想在全国范围内绘制一个完全覆盖的图层。

我构建了一个 JS 函数,它可以调用 Ajax 请求特定国家/地区的 JSON 边界坐标。

收到JSON数据后,我将其应用并绑定到地图对象。

function applyCountryBorder(countryname) {
    var addresssObj = null;

    jQuery.ajax({
        type: 'GET',
        dataType: 'json',
        url: 'https://nominatim.openstreetmap.org/search?country=' + countryname.trim() + '&polygon_geojson=1&format=json',
        async: true,
        cache: true,
        success: function(responseData) {
             var polyline = L.polyline(responseData[0].geojson.coordinates, {
                color: 'green',
                weight: 14,
                opacity: 1    
            }).addTo(map);
            map.invalidateSize();
        },
        error: function(responseData) {
            addresssObj =  responseData;}
    });
}

我希望指定国家/地区的边界有一条明亮、实心、粗的绿线。但实际上,地图和国家边界保持不变并保持默认。

我做错了什么?我怎样才能达到预期的目标?

最有可能的是边界(MultiPolygon 形状)正在渲染,但只是不在您期望的位置。在 GeoJSON 格式中,坐标以 lng,lat 顺序表示,而 L.polyline 期望坐标格式为 lat,lng,换句话说,GeoJSON 坐标 (lng,lat) 需要交换为 lat,lng.

L.GeoJSON.coordsToLatLng() function 可用于该事项,例如

const latLngs = L.GeoJSON.coordsToLatLngs(data[0].geojson.coordinates,2); 
L.polyline(latLngs, {
    color: "green",
    weight: 14,
    opacity: 1
}).addTo(map);

由于提供了服务 returns GeoJSON,另一种选择是利用 L.geoJSON 来呈现这样的边框:

const layer = L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  maxZoom: 19,
  attribution:
    '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
});

const map = L.map("map", {
  layers: [layer]
}).setView([52.8203934, -4.5700609], 6);
applyCountryBorder(map, "United Kingdom");

function applyCountryBorder(map, countryname) {
  jQuery
    .ajax({
      type: "GET",
      dataType: "json",
      url:
        "https://nominatim.openstreetmap.org/search?country=" +
        countryname.trim() +
        "&polygon_geojson=1&format=json"
    })
    .then(function(data) {
      /*const latLngs = L.GeoJSON.coordsToLatLngs(data[0].geojson.coordinates,2) 
      L.polyline(latLngs, {
        color: "green",
        weight: 14,
        opacity: 1
      }).addTo(map);*/

      L.geoJSON(data[0].geojson, {
        color: "green",
        weight: 14,
        opacity: 1,
        fillOpacity: 0.0 
      }).addTo(map);
    });
}
#map {
        width: 100%;
        height: 480px;
      }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link
      rel="stylesheet"
      href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css"
/>
<script src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js"></script>
<div id="map"></div>