Calculate distance from GPX in OpenLayers Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?PostGIS - Calculate progressive distance between points on a GPX pathHow to calculate average distance from points to points?OpenLayers3 with google map local tiles serverRead GPX file from desktop in Openlayers 3Openlayers 3 GPX Shape issueHow to calculate straight line distance from spherical distanceError loading geoJSON into map using OpenLayers v4.2.0how to measure polygon perimeter / Distance in openlayers 3?Does ArcGIS linear distance tool calculate exact distance on ground?Calculate the next coordinate from given starting point and distance

Why do early math courses focus on the cross sections of a cone and not on other 3D objects?

Putting class ranking in CV, but against dept guidelines

What does Turing mean by this statement?

Tannaka duality for semisimple groups

i2c bus hangs in master RPi access to MSP430G uC ~1 in 1000 accesses

What is the role of と after a noun when it doesn't appear to count or list anything?

Nose gear failure in single prop aircraft: belly landing or nose-gear up landing?

Did Mueller's report provide an evidentiary basis for the claim of Russian govt election interference via social media?

Simple HTTP Server

I can't produce songs

How can I prevent/balance waiting and turtling as a response to cooldown mechanics

How to write capital alpha?

The Nth Gryphon Number

How many time has Arya actually used Needle?

Does the Mueller report show a conspiracy between Russia and the Trump Campaign?

Co-worker has annoying ringtone

Why not send Voyager 3 and 4 following up the paths taken by Voyager 1 and 2 to re-transmit signals of later as they fly away from Earth?

If Windows 7 doesn't support WSL, then what is "Subsystem for UNIX-based Applications"?

What is the difference between a "ranged attack" and a "ranged weapon attack"?

Simple Line in LaTeX Help!

Sally's older brother

Why not use the yoke to control yaw, as well as pitch and roll?

Mounting TV on a weird wall that has some material between the drywall and stud

What are the main differences between the original Stargate SG-1 and the Final Cut edition?



Calculate distance from GPX in OpenLayers



Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?PostGIS - Calculate progressive distance between points on a GPX pathHow to calculate average distance from points to points?OpenLayers3 with google map local tiles serverRead GPX file from desktop in Openlayers 3Openlayers 3 GPX Shape issueHow to calculate straight line distance from spherical distanceError loading geoJSON into map using OpenLayers v4.2.0how to measure polygon perimeter / Distance in openlayers 3?Does ArcGIS linear distance tool calculate exact distance on ground?Calculate the next coordinate from given starting point and distance



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I have a little OL script to display GPX Routes in a OSM map. That works so far, even with a little gimmick.



What I miss is a continuous distance. So from trkpt 0 to trkpt 1 + (trkpt 1 to trkpt 2) + (trkpt 2 to trkpt 3) etc.



For the gimmick I use the array keys. Each array key is an (internal) point where data is calculated. In OpenLayers is an array with all coordinates + the elevation. I would like to extend this array by the distance. Whether the array values should be the continuous distance or that from last-trkpt to next-trkpt, I would have to think twice. Maybe a value with last-trkpt to next-trkpt is probably better.



Is there a solution without OL npm. I use only the ol.css and ol.js v5.3.0.



HTML:



<input type="file" id="files" name="files[]" >
<div id="map" class="map"></div>


Javascript:



var gpxFormat = new ol.format.GPX();
var gpxFeatures;
var coordsarray = [];
var GPXgeometry = [];
function handleFileSelect(evt) {

gpxLayer.getSource().clear();

var files = evt.target.files;

var output = [];
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.readAsText(files[i], "UTF-8");
reader.onload = function (evt)
gpxFeatures = gpxFormat.readFeatures(evt.target.result,
dataProjection:'EPSG:4326',
featureProjection:'EPSG:3857'
);
gpxLayer.getSource().addFeatures(gpxFeatures);

var features = gpxLayer.getSource().getFeatures();
features.forEach(function(feature)
GPXgeometry = feature.getGeometry();
coordsarray = feature.getGeometry().getCoordinates();
);

//--- ??? Start

var i = 0;
var distance = 0;
coordsarray[0][i].push(distance):

// for ???

var lat0 = coordsarray[0][i][0];
var lon0 = coordsarray[0][i][1];
var latlon0 = [lat0, lon0];
i++;
var lat1 = coordsarray[0][i][0];
var lon1 = coordsarray[0][i][1];
var latlon1 = [lat1, lon1];

// calculate distance
// ???

coordsarray[0][i].push(distance):
i--;

//--- ??? End




var gpxLayer = new ol.layer.Vector(
source: new ol.source.Vector(

)
);


var map = new ol.Map(
target: 'map',
layers: [
new ol.layer.Tile(
source: new ol.source.OSM()
),
gpxLayer
]
);

document.getElementById('files').addEventListener('change', handleFileSelect, false);


Example of var coordsarray:



console.log(coordsarray[0][0][0]); // -37937.014545402875
console.log(coordsarray[0][0][1]); // 5354259.990656373
console.log(coordsarray[0][0][2]); // 188.5
console.log(coordsarray[0][1][0]); // -37936.012669985736
console.log(coordsarray[0][1][1]); // 5354231.092259876
console.log(coordsarray[0][1][2]); // 188.5


EDIT

GPX Example (near equador)



<?xml version="1.0" encoding="UTF-8"?>
<!-- track-length = 1323 filtered ascend = 0 plain-ascend = -1 cost=4036 energy=.0kwh time=9.9m -->
<gpx
xmlns="http://www.topografix.com/GPX/1/1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"
creator="BRouter-1.4.11" version="1.1">
<trk>
<name>brouter_trekking_0</name>
<trkseg>
<trkpt lon="11.487967" lat="0.332443"><ele>319.0</ele></trkpt>
<trkpt lon="11.488969" lat="0.332369"><ele>318.0</ele></trkpt>
<trkpt lon="11.494446" lat="0.331905"><ele>309.0</ele></trkpt>
<trkpt lon="11.499806" lat="0.331473"><ele>317.0</ele></trkpt>
</trkseg>
</trk>
</gpx>


Javascript:



var startpoint = 0;
var endpoint = startpoint + 2;
var distance = new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)).transform('EPSG:4326','EPSG:3857').getLength();
console.log(distance); // 13065083.453663955 ???









share|improve this question






























    1















    I have a little OL script to display GPX Routes in a OSM map. That works so far, even with a little gimmick.



    What I miss is a continuous distance. So from trkpt 0 to trkpt 1 + (trkpt 1 to trkpt 2) + (trkpt 2 to trkpt 3) etc.



    For the gimmick I use the array keys. Each array key is an (internal) point where data is calculated. In OpenLayers is an array with all coordinates + the elevation. I would like to extend this array by the distance. Whether the array values should be the continuous distance or that from last-trkpt to next-trkpt, I would have to think twice. Maybe a value with last-trkpt to next-trkpt is probably better.



    Is there a solution without OL npm. I use only the ol.css and ol.js v5.3.0.



    HTML:



    <input type="file" id="files" name="files[]" >
    <div id="map" class="map"></div>


    Javascript:



    var gpxFormat = new ol.format.GPX();
    var gpxFeatures;
    var coordsarray = [];
    var GPXgeometry = [];
    function handleFileSelect(evt) {

    gpxLayer.getSource().clear();

    var files = evt.target.files;

    var output = [];
    for (var i = 0, f; f = files[i]; i++) {
    var reader = new FileReader();
    reader.readAsText(files[i], "UTF-8");
    reader.onload = function (evt)
    gpxFeatures = gpxFormat.readFeatures(evt.target.result,
    dataProjection:'EPSG:4326',
    featureProjection:'EPSG:3857'
    );
    gpxLayer.getSource().addFeatures(gpxFeatures);

    var features = gpxLayer.getSource().getFeatures();
    features.forEach(function(feature)
    GPXgeometry = feature.getGeometry();
    coordsarray = feature.getGeometry().getCoordinates();
    );

    //--- ??? Start

    var i = 0;
    var distance = 0;
    coordsarray[0][i].push(distance):

    // for ???

    var lat0 = coordsarray[0][i][0];
    var lon0 = coordsarray[0][i][1];
    var latlon0 = [lat0, lon0];
    i++;
    var lat1 = coordsarray[0][i][0];
    var lon1 = coordsarray[0][i][1];
    var latlon1 = [lat1, lon1];

    // calculate distance
    // ???

    coordsarray[0][i].push(distance):
    i--;

    //--- ??? End




    var gpxLayer = new ol.layer.Vector(
    source: new ol.source.Vector(

    )
    );


    var map = new ol.Map(
    target: 'map',
    layers: [
    new ol.layer.Tile(
    source: new ol.source.OSM()
    ),
    gpxLayer
    ]
    );

    document.getElementById('files').addEventListener('change', handleFileSelect, false);


    Example of var coordsarray:



    console.log(coordsarray[0][0][0]); // -37937.014545402875
    console.log(coordsarray[0][0][1]); // 5354259.990656373
    console.log(coordsarray[0][0][2]); // 188.5
    console.log(coordsarray[0][1][0]); // -37936.012669985736
    console.log(coordsarray[0][1][1]); // 5354231.092259876
    console.log(coordsarray[0][1][2]); // 188.5


    EDIT

    GPX Example (near equador)



    <?xml version="1.0" encoding="UTF-8"?>
    <!-- track-length = 1323 filtered ascend = 0 plain-ascend = -1 cost=4036 energy=.0kwh time=9.9m -->
    <gpx
    xmlns="http://www.topografix.com/GPX/1/1"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"
    creator="BRouter-1.4.11" version="1.1">
    <trk>
    <name>brouter_trekking_0</name>
    <trkseg>
    <trkpt lon="11.487967" lat="0.332443"><ele>319.0</ele></trkpt>
    <trkpt lon="11.488969" lat="0.332369"><ele>318.0</ele></trkpt>
    <trkpt lon="11.494446" lat="0.331905"><ele>309.0</ele></trkpt>
    <trkpt lon="11.499806" lat="0.331473"><ele>317.0</ele></trkpt>
    </trkseg>
    </trk>
    </gpx>


    Javascript:



    var startpoint = 0;
    var endpoint = startpoint + 2;
    var distance = new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)).transform('EPSG:4326','EPSG:3857').getLength();
    console.log(distance); // 13065083.453663955 ???









    share|improve this question


























      1












      1








      1








      I have a little OL script to display GPX Routes in a OSM map. That works so far, even with a little gimmick.



      What I miss is a continuous distance. So from trkpt 0 to trkpt 1 + (trkpt 1 to trkpt 2) + (trkpt 2 to trkpt 3) etc.



      For the gimmick I use the array keys. Each array key is an (internal) point where data is calculated. In OpenLayers is an array with all coordinates + the elevation. I would like to extend this array by the distance. Whether the array values should be the continuous distance or that from last-trkpt to next-trkpt, I would have to think twice. Maybe a value with last-trkpt to next-trkpt is probably better.



      Is there a solution without OL npm. I use only the ol.css and ol.js v5.3.0.



      HTML:



      <input type="file" id="files" name="files[]" >
      <div id="map" class="map"></div>


      Javascript:



      var gpxFormat = new ol.format.GPX();
      var gpxFeatures;
      var coordsarray = [];
      var GPXgeometry = [];
      function handleFileSelect(evt) {

      gpxLayer.getSource().clear();

      var files = evt.target.files;

      var output = [];
      for (var i = 0, f; f = files[i]; i++) {
      var reader = new FileReader();
      reader.readAsText(files[i], "UTF-8");
      reader.onload = function (evt)
      gpxFeatures = gpxFormat.readFeatures(evt.target.result,
      dataProjection:'EPSG:4326',
      featureProjection:'EPSG:3857'
      );
      gpxLayer.getSource().addFeatures(gpxFeatures);

      var features = gpxLayer.getSource().getFeatures();
      features.forEach(function(feature)
      GPXgeometry = feature.getGeometry();
      coordsarray = feature.getGeometry().getCoordinates();
      );

      //--- ??? Start

      var i = 0;
      var distance = 0;
      coordsarray[0][i].push(distance):

      // for ???

      var lat0 = coordsarray[0][i][0];
      var lon0 = coordsarray[0][i][1];
      var latlon0 = [lat0, lon0];
      i++;
      var lat1 = coordsarray[0][i][0];
      var lon1 = coordsarray[0][i][1];
      var latlon1 = [lat1, lon1];

      // calculate distance
      // ???

      coordsarray[0][i].push(distance):
      i--;

      //--- ??? End




      var gpxLayer = new ol.layer.Vector(
      source: new ol.source.Vector(

      )
      );


      var map = new ol.Map(
      target: 'map',
      layers: [
      new ol.layer.Tile(
      source: new ol.source.OSM()
      ),
      gpxLayer
      ]
      );

      document.getElementById('files').addEventListener('change', handleFileSelect, false);


      Example of var coordsarray:



      console.log(coordsarray[0][0][0]); // -37937.014545402875
      console.log(coordsarray[0][0][1]); // 5354259.990656373
      console.log(coordsarray[0][0][2]); // 188.5
      console.log(coordsarray[0][1][0]); // -37936.012669985736
      console.log(coordsarray[0][1][1]); // 5354231.092259876
      console.log(coordsarray[0][1][2]); // 188.5


      EDIT

      GPX Example (near equador)



      <?xml version="1.0" encoding="UTF-8"?>
      <!-- track-length = 1323 filtered ascend = 0 plain-ascend = -1 cost=4036 energy=.0kwh time=9.9m -->
      <gpx
      xmlns="http://www.topografix.com/GPX/1/1"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"
      creator="BRouter-1.4.11" version="1.1">
      <trk>
      <name>brouter_trekking_0</name>
      <trkseg>
      <trkpt lon="11.487967" lat="0.332443"><ele>319.0</ele></trkpt>
      <trkpt lon="11.488969" lat="0.332369"><ele>318.0</ele></trkpt>
      <trkpt lon="11.494446" lat="0.331905"><ele>309.0</ele></trkpt>
      <trkpt lon="11.499806" lat="0.331473"><ele>317.0</ele></trkpt>
      </trkseg>
      </trk>
      </gpx>


      Javascript:



      var startpoint = 0;
      var endpoint = startpoint + 2;
      var distance = new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)).transform('EPSG:4326','EPSG:3857').getLength();
      console.log(distance); // 13065083.453663955 ???









      share|improve this question
















      I have a little OL script to display GPX Routes in a OSM map. That works so far, even with a little gimmick.



      What I miss is a continuous distance. So from trkpt 0 to trkpt 1 + (trkpt 1 to trkpt 2) + (trkpt 2 to trkpt 3) etc.



      For the gimmick I use the array keys. Each array key is an (internal) point where data is calculated. In OpenLayers is an array with all coordinates + the elevation. I would like to extend this array by the distance. Whether the array values should be the continuous distance or that from last-trkpt to next-trkpt, I would have to think twice. Maybe a value with last-trkpt to next-trkpt is probably better.



      Is there a solution without OL npm. I use only the ol.css and ol.js v5.3.0.



      HTML:



      <input type="file" id="files" name="files[]" >
      <div id="map" class="map"></div>


      Javascript:



      var gpxFormat = new ol.format.GPX();
      var gpxFeatures;
      var coordsarray = [];
      var GPXgeometry = [];
      function handleFileSelect(evt) {

      gpxLayer.getSource().clear();

      var files = evt.target.files;

      var output = [];
      for (var i = 0, f; f = files[i]; i++) {
      var reader = new FileReader();
      reader.readAsText(files[i], "UTF-8");
      reader.onload = function (evt)
      gpxFeatures = gpxFormat.readFeatures(evt.target.result,
      dataProjection:'EPSG:4326',
      featureProjection:'EPSG:3857'
      );
      gpxLayer.getSource().addFeatures(gpxFeatures);

      var features = gpxLayer.getSource().getFeatures();
      features.forEach(function(feature)
      GPXgeometry = feature.getGeometry();
      coordsarray = feature.getGeometry().getCoordinates();
      );

      //--- ??? Start

      var i = 0;
      var distance = 0;
      coordsarray[0][i].push(distance):

      // for ???

      var lat0 = coordsarray[0][i][0];
      var lon0 = coordsarray[0][i][1];
      var latlon0 = [lat0, lon0];
      i++;
      var lat1 = coordsarray[0][i][0];
      var lon1 = coordsarray[0][i][1];
      var latlon1 = [lat1, lon1];

      // calculate distance
      // ???

      coordsarray[0][i].push(distance):
      i--;

      //--- ??? End




      var gpxLayer = new ol.layer.Vector(
      source: new ol.source.Vector(

      )
      );


      var map = new ol.Map(
      target: 'map',
      layers: [
      new ol.layer.Tile(
      source: new ol.source.OSM()
      ),
      gpxLayer
      ]
      );

      document.getElementById('files').addEventListener('change', handleFileSelect, false);


      Example of var coordsarray:



      console.log(coordsarray[0][0][0]); // -37937.014545402875
      console.log(coordsarray[0][0][1]); // 5354259.990656373
      console.log(coordsarray[0][0][2]); // 188.5
      console.log(coordsarray[0][1][0]); // -37936.012669985736
      console.log(coordsarray[0][1][1]); // 5354231.092259876
      console.log(coordsarray[0][1][2]); // 188.5


      EDIT

      GPX Example (near equador)



      <?xml version="1.0" encoding="UTF-8"?>
      <!-- track-length = 1323 filtered ascend = 0 plain-ascend = -1 cost=4036 energy=.0kwh time=9.9m -->
      <gpx
      xmlns="http://www.topografix.com/GPX/1/1"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"
      creator="BRouter-1.4.11" version="1.1">
      <trk>
      <name>brouter_trekking_0</name>
      <trkseg>
      <trkpt lon="11.487967" lat="0.332443"><ele>319.0</ele></trkpt>
      <trkpt lon="11.488969" lat="0.332369"><ele>318.0</ele></trkpt>
      <trkpt lon="11.494446" lat="0.331905"><ele>309.0</ele></trkpt>
      <trkpt lon="11.499806" lat="0.331473"><ele>317.0</ele></trkpt>
      </trkseg>
      </trk>
      </gpx>


      Javascript:



      var startpoint = 0;
      var endpoint = startpoint + 2;
      var distance = new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)).transform('EPSG:4326','EPSG:3857').getLength();
      console.log(distance); // 13065083.453663955 ???






      openlayers distance






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 12 at 17:03









      Vince

      14.8k32850




      14.8k32850










      asked Apr 12 at 11:53









      SukaSuka

      416




      416




















          1 Answer
          1






          active

          oldest

          votes


















          2














          Try



          var distance = new ol.geom.LineString(coordsarray[0].slice(0,i+1)).transform('EPSG:4326','????').getLength();


          Ideally transform to a local projection such as UTM which will give meaningful meter distances.



          To scale EPSG:3857 units to a latitude you can use point resolution:



          var center = ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)).getCoordinateAt(0.5);
          var units = new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)‌​).getLength();
          var distance = ol.proj.getPointResolution('EPSG:3857', units, center);


          Over long distances spherical geometry should give a more accurate result, see https://openlayers.org/en/latest/apidoc/module-ol_sphere.html



          var distance = ol.sphere.getLength(new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)‌​));





          share|improve this answer

























          • Hi Mike. Sorry, i don't understand it. var distance = new ol.geom.LineString(coordsarray[0].slice(0,i+1)).transform('EPSG:4326','EPSG:3857').getLength(); console.log(distance); // example: 1234567.123456789. Is there a distance for the complete GPX route in inch?

            – Suka
            Apr 12 at 13:38











          • .getLength will return the distance in the units of the projection you transform the geometry to. For EPSG:3857 the units are meters, but as the scale of EPSG:3857 is true only at the equator it wouldn't give an accurate true distance anywhere outside the tropics and in somewhere like Greenland it would be meaningless. To convert meters to inches divide by 0.0254. coordsarray[0].slice(0,i+1) is the route from start to current point, coordsarray[0].slice(i-1,i+1) would be previous point to current point

            – Mike
            Apr 12 at 13:55











          • Yes, by slice there must be (i,i+2). But, the distance is never correct. I have a example of 160 meters, and var distance = 3986643.790377662?

            – Suka
            Apr 12 at 14:31











          • I have add a GPX example.

            – Suka
            Apr 12 at 14:43











          • Your coordinates were already transformed to EPSG:3857 by readFeatures so (near the equator) var distance = new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)).getLength(); will return meters

            – Mike
            Apr 12 at 14:57











          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "79"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f318600%2fcalculate-distance-from-gpx-in-openlayers%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          Try



          var distance = new ol.geom.LineString(coordsarray[0].slice(0,i+1)).transform('EPSG:4326','????').getLength();


          Ideally transform to a local projection such as UTM which will give meaningful meter distances.



          To scale EPSG:3857 units to a latitude you can use point resolution:



          var center = ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)).getCoordinateAt(0.5);
          var units = new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)‌​).getLength();
          var distance = ol.proj.getPointResolution('EPSG:3857', units, center);


          Over long distances spherical geometry should give a more accurate result, see https://openlayers.org/en/latest/apidoc/module-ol_sphere.html



          var distance = ol.sphere.getLength(new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)‌​));





          share|improve this answer

























          • Hi Mike. Sorry, i don't understand it. var distance = new ol.geom.LineString(coordsarray[0].slice(0,i+1)).transform('EPSG:4326','EPSG:3857').getLength(); console.log(distance); // example: 1234567.123456789. Is there a distance for the complete GPX route in inch?

            – Suka
            Apr 12 at 13:38











          • .getLength will return the distance in the units of the projection you transform the geometry to. For EPSG:3857 the units are meters, but as the scale of EPSG:3857 is true only at the equator it wouldn't give an accurate true distance anywhere outside the tropics and in somewhere like Greenland it would be meaningless. To convert meters to inches divide by 0.0254. coordsarray[0].slice(0,i+1) is the route from start to current point, coordsarray[0].slice(i-1,i+1) would be previous point to current point

            – Mike
            Apr 12 at 13:55











          • Yes, by slice there must be (i,i+2). But, the distance is never correct. I have a example of 160 meters, and var distance = 3986643.790377662?

            – Suka
            Apr 12 at 14:31











          • I have add a GPX example.

            – Suka
            Apr 12 at 14:43











          • Your coordinates were already transformed to EPSG:3857 by readFeatures so (near the equator) var distance = new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)).getLength(); will return meters

            – Mike
            Apr 12 at 14:57















          2














          Try



          var distance = new ol.geom.LineString(coordsarray[0].slice(0,i+1)).transform('EPSG:4326','????').getLength();


          Ideally transform to a local projection such as UTM which will give meaningful meter distances.



          To scale EPSG:3857 units to a latitude you can use point resolution:



          var center = ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)).getCoordinateAt(0.5);
          var units = new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)‌​).getLength();
          var distance = ol.proj.getPointResolution('EPSG:3857', units, center);


          Over long distances spherical geometry should give a more accurate result, see https://openlayers.org/en/latest/apidoc/module-ol_sphere.html



          var distance = ol.sphere.getLength(new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)‌​));





          share|improve this answer

























          • Hi Mike. Sorry, i don't understand it. var distance = new ol.geom.LineString(coordsarray[0].slice(0,i+1)).transform('EPSG:4326','EPSG:3857').getLength(); console.log(distance); // example: 1234567.123456789. Is there a distance for the complete GPX route in inch?

            – Suka
            Apr 12 at 13:38











          • .getLength will return the distance in the units of the projection you transform the geometry to. For EPSG:3857 the units are meters, but as the scale of EPSG:3857 is true only at the equator it wouldn't give an accurate true distance anywhere outside the tropics and in somewhere like Greenland it would be meaningless. To convert meters to inches divide by 0.0254. coordsarray[0].slice(0,i+1) is the route from start to current point, coordsarray[0].slice(i-1,i+1) would be previous point to current point

            – Mike
            Apr 12 at 13:55











          • Yes, by slice there must be (i,i+2). But, the distance is never correct. I have a example of 160 meters, and var distance = 3986643.790377662?

            – Suka
            Apr 12 at 14:31











          • I have add a GPX example.

            – Suka
            Apr 12 at 14:43











          • Your coordinates were already transformed to EPSG:3857 by readFeatures so (near the equator) var distance = new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)).getLength(); will return meters

            – Mike
            Apr 12 at 14:57













          2












          2








          2







          Try



          var distance = new ol.geom.LineString(coordsarray[0].slice(0,i+1)).transform('EPSG:4326','????').getLength();


          Ideally transform to a local projection such as UTM which will give meaningful meter distances.



          To scale EPSG:3857 units to a latitude you can use point resolution:



          var center = ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)).getCoordinateAt(0.5);
          var units = new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)‌​).getLength();
          var distance = ol.proj.getPointResolution('EPSG:3857', units, center);


          Over long distances spherical geometry should give a more accurate result, see https://openlayers.org/en/latest/apidoc/module-ol_sphere.html



          var distance = ol.sphere.getLength(new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)‌​));





          share|improve this answer















          Try



          var distance = new ol.geom.LineString(coordsarray[0].slice(0,i+1)).transform('EPSG:4326','????').getLength();


          Ideally transform to a local projection such as UTM which will give meaningful meter distances.



          To scale EPSG:3857 units to a latitude you can use point resolution:



          var center = ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)).getCoordinateAt(0.5);
          var units = new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)‌​).getLength();
          var distance = ol.proj.getPointResolution('EPSG:3857', units, center);


          Over long distances spherical geometry should give a more accurate result, see https://openlayers.org/en/latest/apidoc/module-ol_sphere.html



          var distance = ol.sphere.getLength(new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)‌​));






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Apr 12 at 18:27

























          answered Apr 12 at 12:09









          MikeMike

          2,565139




          2,565139












          • Hi Mike. Sorry, i don't understand it. var distance = new ol.geom.LineString(coordsarray[0].slice(0,i+1)).transform('EPSG:4326','EPSG:3857').getLength(); console.log(distance); // example: 1234567.123456789. Is there a distance for the complete GPX route in inch?

            – Suka
            Apr 12 at 13:38











          • .getLength will return the distance in the units of the projection you transform the geometry to. For EPSG:3857 the units are meters, but as the scale of EPSG:3857 is true only at the equator it wouldn't give an accurate true distance anywhere outside the tropics and in somewhere like Greenland it would be meaningless. To convert meters to inches divide by 0.0254. coordsarray[0].slice(0,i+1) is the route from start to current point, coordsarray[0].slice(i-1,i+1) would be previous point to current point

            – Mike
            Apr 12 at 13:55











          • Yes, by slice there must be (i,i+2). But, the distance is never correct. I have a example of 160 meters, and var distance = 3986643.790377662?

            – Suka
            Apr 12 at 14:31











          • I have add a GPX example.

            – Suka
            Apr 12 at 14:43











          • Your coordinates were already transformed to EPSG:3857 by readFeatures so (near the equator) var distance = new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)).getLength(); will return meters

            – Mike
            Apr 12 at 14:57

















          • Hi Mike. Sorry, i don't understand it. var distance = new ol.geom.LineString(coordsarray[0].slice(0,i+1)).transform('EPSG:4326','EPSG:3857').getLength(); console.log(distance); // example: 1234567.123456789. Is there a distance for the complete GPX route in inch?

            – Suka
            Apr 12 at 13:38











          • .getLength will return the distance in the units of the projection you transform the geometry to. For EPSG:3857 the units are meters, but as the scale of EPSG:3857 is true only at the equator it wouldn't give an accurate true distance anywhere outside the tropics and in somewhere like Greenland it would be meaningless. To convert meters to inches divide by 0.0254. coordsarray[0].slice(0,i+1) is the route from start to current point, coordsarray[0].slice(i-1,i+1) would be previous point to current point

            – Mike
            Apr 12 at 13:55











          • Yes, by slice there must be (i,i+2). But, the distance is never correct. I have a example of 160 meters, and var distance = 3986643.790377662?

            – Suka
            Apr 12 at 14:31











          • I have add a GPX example.

            – Suka
            Apr 12 at 14:43











          • Your coordinates were already transformed to EPSG:3857 by readFeatures so (near the equator) var distance = new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)).getLength(); will return meters

            – Mike
            Apr 12 at 14:57
















          Hi Mike. Sorry, i don't understand it. var distance = new ol.geom.LineString(coordsarray[0].slice(0,i+1)).transform('EPSG:4326','EPSG:3857').getLength(); console.log(distance); // example: 1234567.123456789. Is there a distance for the complete GPX route in inch?

          – Suka
          Apr 12 at 13:38





          Hi Mike. Sorry, i don't understand it. var distance = new ol.geom.LineString(coordsarray[0].slice(0,i+1)).transform('EPSG:4326','EPSG:3857').getLength(); console.log(distance); // example: 1234567.123456789. Is there a distance for the complete GPX route in inch?

          – Suka
          Apr 12 at 13:38













          .getLength will return the distance in the units of the projection you transform the geometry to. For EPSG:3857 the units are meters, but as the scale of EPSG:3857 is true only at the equator it wouldn't give an accurate true distance anywhere outside the tropics and in somewhere like Greenland it would be meaningless. To convert meters to inches divide by 0.0254. coordsarray[0].slice(0,i+1) is the route from start to current point, coordsarray[0].slice(i-1,i+1) would be previous point to current point

          – Mike
          Apr 12 at 13:55





          .getLength will return the distance in the units of the projection you transform the geometry to. For EPSG:3857 the units are meters, but as the scale of EPSG:3857 is true only at the equator it wouldn't give an accurate true distance anywhere outside the tropics and in somewhere like Greenland it would be meaningless. To convert meters to inches divide by 0.0254. coordsarray[0].slice(0,i+1) is the route from start to current point, coordsarray[0].slice(i-1,i+1) would be previous point to current point

          – Mike
          Apr 12 at 13:55













          Yes, by slice there must be (i,i+2). But, the distance is never correct. I have a example of 160 meters, and var distance = 3986643.790377662?

          – Suka
          Apr 12 at 14:31





          Yes, by slice there must be (i,i+2). But, the distance is never correct. I have a example of 160 meters, and var distance = 3986643.790377662?

          – Suka
          Apr 12 at 14:31













          I have add a GPX example.

          – Suka
          Apr 12 at 14:43





          I have add a GPX example.

          – Suka
          Apr 12 at 14:43













          Your coordinates were already transformed to EPSG:3857 by readFeatures so (near the equator) var distance = new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)).getLength(); will return meters

          – Mike
          Apr 12 at 14:57





          Your coordinates were already transformed to EPSG:3857 by readFeatures so (near the equator) var distance = new ol.geom.LineString(coordsarray[0].slice(startpoint,endpoint)).getLength(); will return meters

          – Mike
          Apr 12 at 14:57

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Geographic Information Systems Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f318600%2fcalculate-distance-from-gpx-in-openlayers%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          រឿង រ៉ូមេអូ និង ហ្ស៊ុយលីយេ សង្ខេបរឿង តួអង្គ បញ្ជីណែនាំ

          Crop image to path created in TikZ? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Crop an inserted image?TikZ pictures does not appear in posterImage behind and beyond crop marks?Tikz picture as large as possible on A4 PageTransparency vs image compression dilemmaHow to crop background from image automatically?Image does not cropTikzexternal capturing crop marks when externalizing pgfplots?How to include image path that contains a dollar signCrop image with left size given

          Romeo and Juliet ContentsCharactersSynopsisSourcesDate and textThemes and motifsCriticism and interpretationLegacyScene by sceneSee alsoNotes and referencesSourcesExternal linksNavigation menu"Consumer Price Index (estimate) 1800–"10.2307/28710160037-3222287101610.1093/res/II.5.31910.2307/45967845967810.2307/2869925286992510.1525/jams.1982.35.3.03a00050"Dada Masilo: South African dancer who breaks the rules"10.1093/res/os-XV.57.1610.2307/28680942868094"Sweet Sorrow: Mann-Korman's Romeo and Juliet Closes Sept. 5 at MN's Ordway"the original10.2307/45957745957710.1017/CCOL0521570476.009"Ram Leela box office collections hit massive Rs 100 crore, pulverises prediction"Archived"Broadway Revival of Romeo and Juliet, Starring Orlando Bloom and Condola Rashad, Will Close Dec. 8"Archived10.1075/jhp.7.1.04hon"Wherefore art thou, Romeo? To make us laugh at Navy Pier"the original10.1093/gmo/9781561592630.article.O006772"Ram-leela Review Roundup: Critics Hail Film as Best Adaptation of Romeo and Juliet"Archived10.2307/31946310047-77293194631"Romeo and Juliet get Twitter treatment""Juliet's Nurse by Lois Leveen""Romeo and Juliet: Orlando Bloom's Broadway Debut Released in Theaters for Valentine's Day"Archived"Romeo and Juliet Has No Balcony"10.1093/gmo/9781561592630.article.O00778110.2307/2867423286742310.1076/enst.82.2.115.959510.1080/00138380601042675"A plague o' both your houses: error in GCSE exam paper forces apology""Juliet of the Five O'Clock Shadow, and Other Wonders"10.2307/33912430027-4321339124310.2307/28487440038-7134284874410.2307/29123140149-661129123144728341M"Weekender Guide: Shakespeare on The Drive""balcony"UK public library membership"romeo"UK public library membership10.1017/CCOL9780521844291"Post-Zionist Critique on Israel and the Palestinians Part III: Popular Culture"10.2307/25379071533-86140377-919X2537907"Capulets and Montagues: UK exam board admit mixing names up in Romeo and Juliet paper"Istoria Novellamente Ritrovata di Due Nobili Amanti2027/mdp.390150822329610820-750X"GCSE exam error: Board accidentally rewrites Shakespeare"10.2307/29176390149-66112917639"Exam board apologises after error in English GCSE paper which confused characters in Shakespeare's Romeo and Juliet""From Mariotto and Ganozza to Romeo and Guilietta: Metamorphoses of a Renaissance Tale"10.2307/37323537323510.2307/2867455286745510.2307/28678912867891"10 Questions for Taylor Swift"10.2307/28680922868092"Haymarket Theatre""The Zeffirelli Way: Revealing Talk by Florentine Director""Michael Smuin: 1938-2007 / Prolific dance director had showy career"The Life and Art of Edwin BoothRomeo and JulietRomeo and JulietRomeo and JulietRomeo and JulietEasy Read Romeo and JulietRomeo and Julieteeecb12003684p(data)4099369-3n8211610759dbe00d-a9e2-41a3-b2c1-977dd692899302814385X313670221313670221