I want to find a distance between 2 coordinates , using 4.16 JavaScript api

1076
9
Jump to solution
02-04-2021 06:33 AM
rajeshesri01
New Contributor II

Please find below code, i want to find distance between 2 coordinates in feet. How can i achieve this in javascript 4.16.

 

@{
Layout = null;
}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Map</title>
<script src="~/lib/jquery/dist/jquery-3.5.1.min.js"></script>
<link rel="stylesheet" href="https://js.arcgis.com/4.16/esri/themes/light/main.css">
<script src="https://js.arcgis.com/4.16/"></script>

<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />


<style>
html, body, #viewDiv {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
.esri-view-width-medium .esri-popup__main-container {
width: 100%;
}
</style>
<script>
var startingLong;
var startingLat;
var vars = {};
var parts = window.parent.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
vars[key] = value;
});
var livePartitionKey = vars.rowKey;
var isInitialized = false;
var map;
var graphicsLayer;
require([
"esri/Map",
"esri/views/MapView",
"esri/widgets/Locate",
"esri/widgets/Track",
"esri/Graphic",
"esri/layers/GraphicsLayer",
"esri/tasks/Locator",
"esri/geometry/support/webMercatorUtils",
"esri/PopupTemplate",
"dojo/number", "dojo/parser",
"dijit/layout/BorderContainer", "dijit/layout/ContentPane", "dojo/domReady!", "esri/widgets/Popup"
], function (Map, MapView, Locate, Track, Graphic, GraphicsLayer, Locator, webMercatorUtils,
PopupTemplate,
number, parser, Popup) {

parser.parse();
var locator = new Locator("https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");

var infoTemplate = new PopupTemplate({
title: "Location",
content: "Address: {Address}"
});

map = new Map({
basemap: "streets-navigation-vector"
});

var simpleLineSymbol = {
type: "simple-line",
color: [226, 119, 40], // orange
width: 2
};

var simpleMarkerSymbol = {
type: "simple-marker",
color: [0, 0, 255], // orange
outline: {
color: [0, 0, 0], // white
width: 1
}
};

var view = new MapView({
container: "viewDiv",
map: map,
center: [-91.656674999999993, 42.028534999999991],
zoom: 14
});

var track1 = new Track({
view: view,
graphic: new Graphic({
symbol: {
type: "simple-marker",
size: "12px",
color: "green",
outline: {
color: "#efefef",
width: "1.5px"
}
}
}),
useHeadingEnabled: false // Don't change orientation of the map
});

//view.ui.add(track1, "top-left");

view.when(function () {
// All the resources in the MapView and the map have loaded. Now execute additional processes
window.parent.disableTableLoader('vehicle_side_map_column');
showVehicleFaultsOnMap();
}, function (error) {
// Use the errback function to handle when the view doesn't load properly
console.log("The view's resources failed to load: ", error);
});
graphicsLayer = new GraphicsLayer();

view.popup.autoOpenEnabled = false;
view.on("click", function (event) {
debugger;
var screenPoint = {
x: event.x,
y: event.y
};

// Search for graphics at the clicked location
view.hitTest(screenPoint).then(function (response) {
debugger;
if (response.results.length) {
for (var cnt = 0; cnt < response.results.length; cnt++) {
if (response.results[cnt].graphic !== undefined
&& response.results[cnt].graphic.attributes !== undefined
&& response.results[cnt].graphic.attributes.FaultName !== undefined) {
debugger;
var faultName = response.results[cnt].graphic.attributes["FaultName"];
var faultDateTime = response.results[cnt].graphic.attributes["FaultDateTime"];
view.popup.open({
location: event.mapPoint, // location of the click on the view
title: faultName+" Fault", // title displayed in the popup
content: "on " + faultDateTime // content displayed in the popup
});
return;
}
}
}
});
});

function showVehicleFaultsOnMap() {
debugger;
if (window.parent.healthLocation != null || window.parent.healthLocation != undefined) {
var totalFaults = window.parent.healthLocation.length;

for (var cnt = 0; cnt < totalFaults; cnt++) {

var faultData = window.parent.healthLocation[cnt].split(",");

var lat = faultData[0].split(":")[1];
var long = faultData[1].split(":")[1];

var point = {
type: "point",
longitude: long,
latitude: lat
};

var graphicsLayer = new GraphicsLayer();

var simpleMarkerSymbol = {
type: "picture-marker",
url: "/images/alert.png",
width: "24px",
height: "24px"
};

var pointGraphic = new Graphic({
geometry: point,
symbol: simpleMarkerSymbol,
attributes: { "FaultName": faultData[2], "FaultDateTime": window.parent.healthLocationOccuredOn }
});

graphicsLayer.add(pointGraphic);

// Add text below the pin
var textGraphic = new Graphic({
geometry: {
type: "point",
longitude: long,
latitude: lat
},
symbol: {
type: "text",
color: [24, 24, 24],
haloColor: [254, 254, 254],
haloSize: "1px",
text: "",
xoffset: 0,
yoffset: -25,
font: {
size: 12
}
}
});

graphicsLayer.add(textGraphic);
map.add(graphicsLayer);
}

if (totalFaults > 0) {
var firstFaultData = window.parent.healthLocation[0].split(",");
var centerLat = firstFaultData[0].split(":")[1];
var centerLong = firstFaultData[1].split(":")[1];

view.center = [centerLong, centerLat];
view.zoom = 10;
}
}
};

window.streamObserver.subscribe(function (stream, partitionKey, module) {
if ("gps" == module) {
if (partitionKey == livePartitionKey) {

var gpsData = JSON.parse(stream);

var latitudeDegree = gpsData["LocationEventData"]["Latitude"]["Degree"];

var longitudeDegree = gpsData["LocationEventData"]["Longitude"]["Degree"];

updateLeftPanel(gpsData);

if (!isInitialized) {
startingLong = parseFloat(longitudeDegree);
startingLat = parseFloat(latitudeDegree);
isInitialized = true;
addStartingPointintoMap(startingLong, startingLat);
return;
}

var currentLong = parseFloat(longitudeDegree);
var currentLat = parseFloat(latitudeDegree);

vehicleLat = currentLat;
vehicleLong = currentLong;

if (isInitialized) {
var polyline2 = {
type: "polyline",
paths: [
[currentLong, currentLat],
[startingLong, startingLat]
]
};

var polylineGraphic1 = new Graphic({
geometry: polyline2,
symbol: simpleLineSymbol
});

 

var endPoint = {
type: "point",
longitude: currentLong,
latitude: currentLat
};

var pointGraphic1 = new Graphic({
geometry: endPoint,
symbol: simpleMarkerSymbol
});

//graphicsLayer.add(pointGraphic1);
graphicsLayer.add(polylineGraphic1);

//var textGraphic1 = new Graphic({
// geometry: {
// type: "point",
// longitude: -91.656674999999993,
// latitude: 42.028534999999991
// },
// symbol: {
// type: "text",
// color: [25, 25, 25],
// haloColor: [255, 255, 255],
// haloSize: "1px",
// text: "This is my location!",
// xoffset: 0,
// yoffset: -25,
// font: {
// size: 12
// }
// }
//});

//graphicsLayer.add(textGraphic1);
map.add(graphicsLayer);

startingLong = parseFloat(currentLong);
startingLat = parseFloat(currentLat);


}
}
}
});

function addStartingPointintoMap(long, lat) {

pictureGraphic = new Graphic({
geometry: {
type: "point",
longitude: long,
latitude: lat
},
symbol: {
type: "picture-marker",
url: "/images/circle.png",
width: "14px",
height: "14px"
}
});
graphicsLayer.add(pictureGraphic);
view.center = [long, lat]
}
});

function updateLeftPanel(locationXmlDoc) {
try {
var odometer = parseFloat(locationXmlDoc["LocationEventData"]["Extensions"]["Odometer"]).toFixed(1);
var speedOverGround = parseFloat(locationXmlDoc["LocationEventData"]["SpeedOverGround"]).toFixed(0);

window.parent.document.getElementById("odometer").innerHTML = isNaN(odometer) ? 0 : odometer;
window.parent.document.getElementById("speed").innerHTML = isNaN(speedOverGround) ? 0 : speedOverGround;
} catch (e) {
console.log("Can't find data for odometer and speed over ground");
}
}
</script>
</head>
<body>
<div id="viewDiv" style="cursor:pointer"></div>
<div class="container">
<main role="main" class="pb-3">
</main>
</div>
</body>
</html>

0 Kudos
1 Solution

Accepted Solutions
BlakeTerhune
MVP Regular Contributor

Here's the basic format for using geodesicDistance()

 

var firstPoint = new Point({
  longitude: -111.022887,
  latitude: 35.02741
});
var otherPoint = new Point({
  longitude: -111.122887,
  latitude: 35.12741
});
var distanceUnits = "kilometers";
var distanceResult = geodesicUtils.geodesicDistance(firstPoint, otherPoint, distanceUnits);
console.log(distanceResult.distance, distanceUnits);

 

 

Again though, make sure you require "esri/geometry/support/geodesicUtils" and include geodesicUtils in the function parameters.

EDIT:
Sorry, forgot you'll also need to require "esri/geometry/Point" and include Point in the function parameters for this particular example. Here's a sample app.

 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
    <title>Intro to MapView - Create a 2D map | Sample | ArcGIS API for JavaScript 4.18</title>
    <style>
      html,
      body,
      #viewDiv {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
      }
    </style>

    <link rel="stylesheet" href="https://js.arcgis.com/4.18/esri/themes/light/main.css" />
    <script src="https://js.arcgis.com/4.18/"></script>

    <script>
      require(["esri/Map", "esri/views/MapView", "esri/geometry/Point", "esri/geometry/support/geodesicUtils"],
      function(Map, MapView, Point, geodesicUtils) {
        // Set up basic map
        var map = new Map({
          basemap: "topo-vector"
        });
        var view = new MapView({
          container: "viewDiv",
          map: map,
          zoom: 4,
          center: [-111, 35] // longitude, latitude
        });
        
        // Define points for measurement
        var firstPoint = new Point({
          longitude: -111.022887,
          latitude: 35.02741
        });
        var otherPoint = new Point({
          longitude: -111.122887,
          latitude: 35.12741
        });
        
        // Measure distance and output result to console log
        var distanceUnits = "kilometers";
        var distanceResult = geodesicUtils.geodesicDistance(firstPoint, otherPoint, distanceUnits);
        console.log(distanceResult.distance, distanceUnits);
      });
    </script>
  </head>

  <body>
    <div id="viewDiv"></div>
  </body>
</html>

 

View solution in original post

9 Replies
BlakeTerhune
MVP Regular Contributor

You could use point.distance() or geometry engine distance() or geodesicUtils geodesicDistance() or geometryEngineAsync distance() or geometry service distance().

0 Kudos
rajeshesri01
New Contributor II

Thanks for replying , i tried but not success , can you please update above code, so that i get clear solution.

0 Kudos
JohnGrayson
Esri Regular Contributor

It helps to have a very simple CodePen showing just the code related to the issue so we can experience the problem and make suggestions.

0 Kudos
rajeshesri01
New Contributor II

Even a short code will make big help.

0 Kudos
rajeshesri01
New Contributor II

I tried but all giving undefined/not a method error in JavaScript that's why it would be great if provided code.

0 Kudos
BlakeTerhune
MVP Regular Contributor

Did you add the module in the require statement at the top?

0 Kudos
rajeshesri01
New Contributor II

Yes , i tried.

0 Kudos
BlakeTerhune
MVP Regular Contributor

Here's the basic format for using geodesicDistance()

 

var firstPoint = new Point({
  longitude: -111.022887,
  latitude: 35.02741
});
var otherPoint = new Point({
  longitude: -111.122887,
  latitude: 35.12741
});
var distanceUnits = "kilometers";
var distanceResult = geodesicUtils.geodesicDistance(firstPoint, otherPoint, distanceUnits);
console.log(distanceResult.distance, distanceUnits);

 

 

Again though, make sure you require "esri/geometry/support/geodesicUtils" and include geodesicUtils in the function parameters.

EDIT:
Sorry, forgot you'll also need to require "esri/geometry/Point" and include Point in the function parameters for this particular example. Here's a sample app.

 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
    <title>Intro to MapView - Create a 2D map | Sample | ArcGIS API for JavaScript 4.18</title>
    <style>
      html,
      body,
      #viewDiv {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
      }
    </style>

    <link rel="stylesheet" href="https://js.arcgis.com/4.18/esri/themes/light/main.css" />
    <script src="https://js.arcgis.com/4.18/"></script>

    <script>
      require(["esri/Map", "esri/views/MapView", "esri/geometry/Point", "esri/geometry/support/geodesicUtils"],
      function(Map, MapView, Point, geodesicUtils) {
        // Set up basic map
        var map = new Map({
          basemap: "topo-vector"
        });
        var view = new MapView({
          container: "viewDiv",
          map: map,
          zoom: 4,
          center: [-111, 35] // longitude, latitude
        });
        
        // Define points for measurement
        var firstPoint = new Point({
          longitude: -111.022887,
          latitude: 35.02741
        });
        var otherPoint = new Point({
          longitude: -111.122887,
          latitude: 35.12741
        });
        
        // Measure distance and output result to console log
        var distanceUnits = "kilometers";
        var distanceResult = geodesicUtils.geodesicDistance(firstPoint, otherPoint, distanceUnits);
        console.log(distanceResult.distance, distanceUnits);
      });
    </script>
  </head>

  <body>
    <div id="viewDiv"></div>
  </body>
</html>

 

rajeshesri01
New Contributor II

This worked , i including the modules at last. My be this creating a problem. Thanks for help.

0 Kudos