使用JSON坐标在leaflet地图上绘制国家边界。

3

我有一张leaflet地图,和一个长的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;}
    });
}

我希望指定国家的边界具有鲜明、坚实、厚重、绿色的线条,但实际上地图和国家边界保持不变并保持默认状态。我做错了什么?如何实现期望的目标?

也许这个答案可以帮助解决问题。 - N8888
1个回答

4
很可能边框(多边形形状)正在被渲染,但它只是没有出现在您期望的位置上。在GeoJSON格式中,坐标以lng,lat顺序表示,而L.polyline则希望以lat,lng格式表示坐标,换句话说,GeoJSON坐标(lng,lat)需要交换为lat,lng
可以利用L.GeoJSON.coordsToLatLng()函数来完成这个操作,例如:
const latLngs = L.GeoJSON.coordsToLatLngs(data[0].geojson.coordinates,2); 
L.polyline(latLngs, {
    color: "green",
    weight: 14,
    opacity: 1
}).addTo(map);

由于一个提供的服务返回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>


如何只获取边框而不包含填充颜色?显然,这会同时绘制边框和填充层的颜色。是否可能仅具有实心边框,但透明填充? - Morgan Janjua Crane
@MorganJanjuaCrane,我猜你想要的是 fillOpacity: 0.0 属性,示例已经更新。 - Vadim Gremyachev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接