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

时间:2019-03-22 22:33:59

标签: javascript json leaflet polygon openstreetmap

我有一张传单地图,并且在长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;}
    });
}

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

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

1 个答案:

答案 0 :(得分:1)

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

例如,

L.GeoJSON.coordsToLatLng() function可以被利用

lat,lng

由于提供的服务返回了GeoJSON,另一种选择是利用L.geoJSON渲染这样的边框:

const latLngs = L.GeoJSON.coordsToLatLngs(data[0].geojson.coordinates,2); 
L.polyline(latLngs, {
    color: "green",
    weight: 14,
    opacity: 1
}).addTo(map);
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;
      }

相关问题