0

enter image description here

I'm working to plot ways using OSM and leaflet using node as a back end. On the front end I have leaflet2.html which has the following in the script tag:

  const mymap = L.map("map");

  async function getGeoJSONArr() {
    const response = await fetch("http://localhost:3000/data");
    const jsonArr = await response.json();
    console.log("jsonARR", jsonArr);
    const reversedCoords = jsonArr[0].slice().reverse();
    console.log(reversedCoords);
    return { jsonArr: jsonArr, reversedCoords: reversedCoords };
  }

  (async function buildMap(params) {
    const o = await getGeoJSONArr();
    console.log(o);
    const polyline1 = o.jsonArr;
    const reversedCoords = o.reversedCoords;
    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      attribution:
        'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors',
      maxZoom: 18,
    }).addTo(mymap);

    mymap.setView(reversedCoords, 13);

    // Add a polyline

    L.polyline(polyline1, { color: "blue" }).addTo(mymap);

   })();

In the console I see:

{jsonArr: Array(5), 
reversedCoords: Array(2)}jsonArr: Array(5)0: (2) [-110.9582708, 31.9323673]

1: (2) [-110.9579731, 31.9323537]2: (2) [-110.9576486, 31.9323673]3: (2) [-110.955342, 31.931959]4: (2) [-110.952628, 31.931936]length: 5[[Prototype]]: Array(0)
reversedCoords: (2) [31.9323673, -110.9582708][[Prototype]]: Object

There are no errors.

I'm expecring to see a polyline on the map, but I don't see it. What am I doing wrong?

1 Answer 1

0

I think I know what you are doing wrong, because a week ago I kept doing the same error -

When you are using a service (for example OSRM or Nominatim) returning geoJSON data, then it is wrong to try to reverse the latitudes, longitudes and to draw L.polylines manually.

Instead you should add the geoJSON data to a L.geoJSON layer (and not directly to mymap as can be seen in the code snippet in your question) and that layer will perform the correct drawing for you.

Here a small demo by me to demonstrate this approach, note how I call routesGroup.addData(route.geometry); there and the blue route line is drawn automatically:

Open Street Map with 2 markers and OSRM route

'use strict';

function processOsrmReply(data) {

  myMap.flyToBounds(markersGroup.getBounds());

  if (data.code !== 'Ok') {
    clearMap('Error code: ' + data.code);
    return;
  }

  data.routes.forEach(function(route) {
    routesGroup.addData(route.geometry);
  });
}

function sendOsrmRequest() {
  var url = 'https://router.project-osrm.org/route/v1/car/' +
    parseFloat(startMarker.getLatLng().lng).toFixed(6) + ',' +
    parseFloat(startMarker.getLatLng().lat).toFixed(6) + ';' +
    parseFloat(finalMarker.getLatLng().lng).toFixed(6) + ',' +
    parseFloat(finalMarker.getLatLng().lat).toFixed(6) +
    '?overview=simplified' +
    '&alternatives=2' +
    '&steps=false' +
    '&annotations=false' +
    '&geometries=geojson';

  var request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.onload = function() {
    if (this.status >= 200 && this.status < 400) {
      var data = JSON.parse(this.response);
      processOsrmReply(data);
    } else {
      clearMap('Error status: ' + this.status);
    }
  };
  request.send();
}

function clearMap(str = '') {
  var myStatus = document.getElementById('myStatus');
  myStatus.textContent = str;
  routesGroup.clearLayers();
}

var startPosition = [31.9322, -110.9583];
var finalPosition = [31.9319, -110.9526];

var myMap = L.map('myMap').setView(startPosition, 14);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(myMap);

var markersGroup = L.featureGroup();
myMap.addLayer(markersGroup);
var routesGroup = L.geoJSON();
myMap.addLayer(routesGroup);

var overlays = {
  'Show start and finish markers': markersGroup,
  'Show OSRM route geometry': routesGroup
};

L.control.layers(null, overlays, {
  collapsed: false
}).addTo(myMap);

var startMarker = L.marker(startPosition, {
    draggable: true,
    title: 'start'
  })
  .on('dragend', sendOsrmRequest)
  .addTo(markersGroup);

var finalMarker = L.marker(finalPosition, {
    draggable: true,
    title: 'finish'
  })
  .on('dragend', sendOsrmRequest)
  .addTo(markersGroup);

sendOsrmRequest();
html,
body {
  margin: 0;
  padding: 0;
}

#myMap {
  position: absolute;
  top: 2em;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
}

#myStatus {
  position: absolute;
  z-index: 2;
  width: 100%;
  text-align: center;
}
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1/dist/leaflet.min.css">
<script src="https://cdn.jsdelivr.net/npm/leaflet@1/dist/leaflet-src.min.js"></script>

<div id="myStatus">Drag the 2 markers to calculate the OSRM route</div>
<div id="myMap"></div>

Not the answer you're looking for? Browse other questions tagged or ask your own question.