I have a leaflet map, and I have a set of country borders in a long JSON file. I am trying to use the JSON coordinates to draw a solid green border along the border of a country displayed in the map object.
I do not want to draw a fully covered layer over the country either.
I have built a JS function that makes an Ajax call to request JSON border coordinates for a specific country.
When the JSON data is received, I apply and bound it to the map object.
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;}
});
}
I expect the border of the specified country to have a bright, solid, thick, green line. But actually, the map and country borders remain unchanged and remain default.
What am I doing wrong? How can I achieve the desired goal?
Most likely border (MultiPolygon shape) is getting rendered but just not on the place you expect it to. In GeoJSON format coordinates are represented in lng,lat
order while L.polyline
expects the coordinates in format lat,lng
, in another words GeoJSON coordinates (lng,lat
) needs to swapped to lat,lng
.
L.GeoJSON.coordsToLatLng()
function could be utilized for that matter, for example
const latLngs = L.GeoJSON.coordsToLatLngs(data[0].geojson.coordinates,2);
L.polyline(latLngs, {
color: "green",
weight: 14,
opacity: 1
}).addTo(map);
Since a provided service returns GeoJSON, another option would be to utilize L.geoJSON
to render a border like this:
const layer = L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
maxZoom: 19,
attribution:
'© <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>