Can't display data captured through Json in for loop - javascript

$.getJSON("https://example.com//json/", function (data) {
var count = Object.keys(data).length;
for (var i = 0; i < count; i++) {
var lat = data[i].LAT;
var lng = data[i].LNG;
var locs = { lat: lat, lng: lng };
var check = arePointsNear(pos, locs, 2487);
if (check) listStations.push(data[i].ID);
}
console.log(listStations);
console.log(listStations[0]);
});
function arePointsNear(checkPoint, centerPoint, m) {
var km = m/1000;
var ky = 40000 / 360;
var kx = Math.cos(Math.PI * centerPoint.lat / 180) * ky;
var dx = Math.abs(centerPoint.lng - checkPoint.lng) * kx;
var dy = Math.abs(centerPoint.lat - checkPoint.lat) * ky;
return Math.sqrt(dx * dx + dy * dy) <= km;
}
Example json in data;
{
"ID": 359,
"NAME": "Atatürk Bulvarı 1",
"LOCATION": "0001 Atatürk Bulvarı 1",
"PARK_INFO": "2",
"PARK_CAPACITY": 18,
"START_TIME": {
"Ticks": 270000000000,
"Days": 0,
"Hours": 7,
"Milliseconds": 0,
"Minutes": 30,
"Seconds": 0,
"TotalDays": 0.3125,
"TotalHours": 7.5,
"TotalMilliseconds": 27000000,
"TotalMinutes": 450,
"TotalSeconds": 27000
},
"FINISH_TIME": {
"Ticks": 666000000000,
"Days": 0,
"Hours": 18,
"Milliseconds": 0,
"Minutes": 30,
"Seconds": 0,
"TotalDays": 0.77083333333333326,
"TotalHours": 18.5,
"TotalMilliseconds": 66600000,
"TotalMinutes": 1110,
"TotalSeconds": 66600
},
"DISTRICT_CODE": "20",
"ADRESS": "KEMALPAŞA MAHALLESİ ATATÜRK BULVARI 1 / EMİNÖNÜ",
"LNG": 28.9535382991555,
"LAT": 41.0112914996693,
"SUBS_PRICE": 0,
"FREE_TIME": 15
}
It is ok to pull json data from the relevant link. Sending the data to the arePointsNear function and verifying true-false is ok. When I write the console.log data written in the code in the bottom line (in for), 0.index is undefined.
By the way, variables are defined independently and globally at the top.
What should I do?

You might consider using $.each(). Assuming you're data is an Array of Objects, consider this example.
$(function() {
function arePointsNear(checkPoint, centerPoint, m) {
var km = m / 1000;
var ky = 40000 / 360;
var kx = Math.cos(Math.PI * centerPoint.lat / 180) * ky;
var dx = Math.abs(centerPoint.lng - checkPoint.lng) * kx;
var dy = Math.abs(centerPoint.lat - checkPoint.lat) * ky;
return Math.sqrt(dx * dx + dy * dy) <= km;
}
var pos;
var listStations = [];
$.getJSON("https://example.com/json/", function(data) {
$.each(data, function(index, location) {
if (arePointsNear(pos, {
lat: location.LAT,
lng: location.LNG
}, 2487)) {
listStations.push(location.ID);
}
});
console.log(listStations);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

How to check if a point is near to any other point in an array Javascript

I found an answer here that determines if two points are near each other based on a certain radius:
Check if a latitude and longitude is within a circle google maps
This is not the exact answer I am looking for however as I want to rewrite this function:
function arePointsNear(checkPoint, centerPoint, km) {
var ky = 40000 / 360;
var kx = Math.cos(Math.PI * centerPoint.lat / 180.0) * ky;
var dx = Math.abs(centerPoint.lng - checkPoint.lng) * kx;
var dy = Math.abs(centerPoint.lat - checkPoint.lat) * ky;
return Math.sqrt(dx * dx + dy * dy) <= km;
}
To be able to check if the point of interest is within a certain distance of any other point in the array. Here is my attempt so far but does not work as expected:
function arePointsNear(checkPoint, centerPointArray, km) {
var ky = 40000 / 360;
for (var i = 0; i < centerPointArray.length; i++) {
var kx = Math.cos(Math.PI * centerPointArray[i].lat / 180.0) * ky;
var dx = Math.abs(centerPointArray[i].lng - checkPoint.lng) * kx;
var dy = Math.abs(centerPointArray[i].lat - checkPoint.lat) * ky;
if (Math.sqrt(dx * dx + dy * dy) <= km) {
return true;
} else {
return false;
}
}
}
var centerPointArray = [
{ lat: -42.734358, lng: 147.439506, info: "T" },
{ lat: -42.735258, lng: 147.438000, info: "V" },
{ lat: -43.999792, lng: 170.463352, info: "W" }
]
Here is a link to the JS Fiddle:
https://jsfiddle.net/ohb4puj2/3/
Upon opening up the debugger it does not return the desired result when the markers are moved to within a 10KM radius of each other
Using filter() you can reduce the array down to the places that are within range.
function arePointsNear(checkPoint, centerPoint, km) {
var ky = 40000 / 360;
var kx = Math.cos(Math.PI * centerPoint.lat / 180.0) * ky;
var dx = Math.abs(centerPoint.lng - checkPoint.lng) * kx;
var dy = Math.abs(centerPoint.lat - checkPoint.lat) * ky;
return Math.sqrt(dx * dx + dy * dy) <= km;
}
var centerPointArray = [
{ lat: -42.734358, lng: 147.439506, info: "T" },
{ lat: -42.735258, lng: 147.438000, info: "V" },
{ lat: -43.999792, lng: 170.463352, info: "W" }
]
const checkPoint = { lat: -42.5, lng: 147.4 };
const distance = 50;
const withInRange = centerPointArray.filter( function (centerPoint) {
return arePointsNear(checkPoint, centerPoint, distance);
});
console.log(withInRange);
I think the solution is simple: just take the return false statement out of the for loop. This way, you will return false only if no point in the array was close enough. (right now, you return false if the first point is not close enough)
function arePointsNear(checkPoint, centerPointArray, km) {
var ky = 40000 / 360;
for (var i = 0; i < centerPointArray.length; i++) {
var kx = Math.cos(Math.PI * centerPointArray[i].lat / 180.0) * ky;
var dx = Math.abs(centerPointArray[i].lng - checkPoint.lng) * kx;
var dy = Math.abs(centerPointArray[i].lat - checkPoint.lat) * ky;
if (Math.sqrt(dx * dx + dy * dy) <= km)
return true;
}
return false;
}

Limit array of objects in radius and sort by distance

In node.js have an array of objects contain some coordinates with a specific format
{name:"samplename",location:[longtitude , latitude] }
Also in two variables I am hondling my center point and a radius in meters
var center =[ 12 , -4.32 ]; var radius = 30000;
My goal is to create a function that will return all the spots with maximum distance of 30000 meters from the center sorted by distance.
Example input data given
var spots=[
{name :"spot1",location:[113,32.21] } ,
{name :"spot2",location:[112,-32.21] } ,
{name :"spot3",location:[-33,32.11] } ,
{name :"spot4",location:[113.4,35.21] } ,
{name :"spot5",location:[11,31.21] }
];
var center =[ 12 , -4.32 ]; var radius = 30000;
var finalspots = Calculatedistance(spots, center, radius)
Example output
{name :"spot2",location:[112,-32.21], distance:300 } ,
{name :"spot1",location:[113,32.21] , distance:1400 } ,
{name :"spot5",location:[11,31.21], distance:5000 }
P.S I have fetched Underscore.js into my project for easy object and arrays manipulation
Here you go:
function distanceInMeters (lat1, lon1, lat2, lon2) {
var R = 6371;
var f1 = lat1 * Math.PI / 180;
var f2 = lat2 * Math.PI / 180;
var dlat = (lat2 - lat1) * Math.PI / 180;
var dlon = (lon2 - lon1) * Math.PI / 180;
var a = Math.sin(dlat / 2) * Math.sin(dlat / 2) +
Math.cos(f1) * Math.cos(f2) *
Math.sin(dlon / 2) * Math.sin(dlon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = Math.round(R * c * 1000);
return d;
}
function sortCallback (a, b) {
if (a.distance < b.distance)
return -1;
if (a.distance > b.distance)
return 1;
return 0;
}
function Calculatedistance (spots, center, radius) {
var filteredSpots = [];
for (var i = 0; i < spots.length; i++) {
var spot = spots[i];
var distance = distanceInMeters(center[0], center[1], spot.location[0], spot.location[1]);
if (distance < radius) {
spot.distance = distance;
filteredSpots.push(spot);
}
}
var sortedSpots = filteredSpots.sort(sortCallback);
return sortedSpots;
}
var spots = [
{name: "spot1", location: [113, 32.21]},
{name: "spot2", location: [112, -32.21]},
{name: "spot3", location: [-33, 32.11]},
{name: "spot4", location: [113.4, 35.21]},
{name: "spot5", location: [11, 31.21]}
];
var center = [12, -4.32];
var radius = 10746486;
var finalspots = Calculatedistance(spots, center, radius);
console.log(finalspots);

How to sort array items by longitude latitude distance in javascripts?

I am having following JSON array of 6 locations. Is there any way sort these based on longitude and latitude where nearby locations come next in the array?
[
{"id" : 279, "longitude":79.853239,"latitude":6.912283},
{"id" : 284, "longitude":79.865699,"latitude":6.885697},
{"id" : 13, "longitude":79.851187,"latitude":6.912220},
{"id" : 282, "longitude":79.858904,"latitude":6.871041},
{"id" : 281, "longitude":79.853346,"latitude":6.899757},
{"id" : 16, "longitude":79.854786,"latitude":6.894039}
]
Sorting can be started from first item and result should be something like this
[
{"id" : 279, "longitute":79.853239,"latitude":6.912283},
{"id" : 13, "longitute":79.851187,"latitude":6.912220},
{"id" : 281, "longitute":79.853346,"latitude":6.899757},
{"id" : 16, "longitute":79.854786,"latitude":6.894039},
{"id" : 284, "longitute":79.865699,"latitude":6.885697},
{"id" : 282, "longitute":79.858904,"latitude":6.871041}
]
Problem resolved by adding another attribute called distance. Used following function to calculate distance between two points
function calculateDistance(lat1, lon1, lat2, lon2, unit) {
var radlat1 = Math.PI * lat1/180
var radlat2 = Math.PI * lat2/180
var radlon1 = Math.PI * lon1/180
var radlon2 = Math.PI * lon2/180
var theta = lon1-lon2
var radtheta = Math.PI * theta/180
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist)
dist = dist * 180/Math.PI
dist = dist * 60 * 1.1515
if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }
return dist
}
Then calculated distance for each item in the array by using above function. Then sorted array by distance.
for ( i = 0; i < uniqueNodes.length; i++) {
uniqueNodes[i]["distance"] = calculateDistance(uniqueNodes[0]["latitude"],uniqueNodes[0]["longitute"],uniqueNodes[i]["latitude"],uniqueNodes[i]["longitute"],"K");
}
uniqueNodes.sort(function(a, b) {
return a.distance - b.distance;
});
Anyone else looking to do this, if you have the longitude and latitude avaliable, you can just sort linearly on it to get a simple line diagram like below. this will give you a rise/run linear result.
var $array = [
[79.853239, 6.912283, 279],
[79.851187, 6.912220, 13],
[79.853346, 6.899757, 281],
[79.854786, 6.894039, 16],
[79.865699, 6.885697, 284],
[79.858904, 6.87104, 282]
]
function sortLngLat(a, b){
var x = a[0] / a[1];
var y = b[0] / b[1];
}
var sortedArray = $array.sort(sortLngLat);
console.log(sortedArray);
output should be like graph below and you can tweak your values with negatives and positives to get different angles and directions.
---------------
| | / |
| -1/1 | / 1/1 |
| |/ |
|--------------
| /| |
|-1/-1/ | 1/-1 |
| / | |
---------------
For sorting we only need to calculate the relative distances between points. This allows for some performance optimizations. You don't need to multiply by the earth's radius and you don't need to take the square root of the squared differences.
// define local constants for frequently used functions
const asin = Math.asin
const cos = Math.cos
const sin = Math.sin
const PI_180 = Math.PI / 180
function hav(x) {
const s = sin(x / 2)
return s * s
}
function relativeHaversineDistance(lat1, lon1, lat2, lon2) {
const aLatRad = lat1 * PI_180
const bLatRad = lat2 * PI_180
const aLngRad = lon1 * PI_180
const bLngRad = lon2 * PI_180
const ht = hav(bLatRad - aLatRad) + cos(aLatRad) * cos(bLatRad) * hav(bLngRad - aLngRad)
// since we're only interested in relative differences,
// there is no need to multiply by earth radius or to sqrt the squared differences
return asin(ht)
}
const locations = [
{ "id": 279, "longitude": 79.853239, "latitude": 6.912283 },
{ "id": 284, "longitude": 79.865699, "latitude": 6.885697 },
{ "id": 13, "longitude": 79.851187, "latitude": 6.912220 },
{ "id": 282, "longitude": 79.858904, "latitude": 6.871041 },
{ "id": 281, "longitude": 79.853346, "latitude": 6.899757 },
{ "id": 16, "longitude": 79.854786, "latitude": 6.894039 }
]
const distanceTo = {
"id": 279,
"longitude": 79.853239,
"latitude": 6.912283
}
const sorted = locations.sort((a, b) => relativeHaversineDistance(a.latitude, a.longitude, distanceTo.latitude, distanceTo.longitude) - relativeHaversineDistance(b.latitude, b.longitude, distanceTo.latitude, distanceTo.longitude))
console.log(sorted)
Try to use this one:
function calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371e3; // metres
const φ1 = lat1 * Math.PI / 180; // φ, λ in radians
const φ2 = lat2 * Math.PI / 180;
const Δφ = (lat2 - lat1) * Math.PI / 180;
const Δλ = (lon2 - lon1) * Math.PI / 180;
const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c // in metres
}
You could loop through the array, and nest another loop that finds the nearest one.
var finalArray = [];
while(entries){
//for each item
while(what's left){
//find the nearest against the current item
//push to final
}
}
This assumes that the very first in the array is the point of reference, that what comes next would be the nearest to that point, and so on.

Haversine Formula - Results Too High

I am using the Haversine formula to calculate the distance between two points on earth. I have the following code:
var app = angular.module('app', []);
app.controller('firstCtrl', function($scope, $timeout) {
var myLat, myLon, locLat, locLon;
navigator.geolocation.watchPosition(GetLocation)
$scope.ASiteLocs = [{
"name": "IL5077 BRUSSELS",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.58543899999999,38.955472,0"
}
}, {
"name": "IL5076 KAMPSVILLE",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.661923,39.29403,0"
}
}, {
"name": "IL5146 CARROLLTON",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.39965700000001,39.309142,0"
}
}, {
"name": "IL5153 GREENFIELD",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.208747,39.364077,0"
}
}];
$scope.SSiteLocs = [];
$scope.SiteLocs = $scope.SSiteLocs.concat($scope.ASiteLocs);
repoSortOrder = "site.name";
function GetLocation(location, myLat, myLon) {
myLat = location.coords.latitude;
myLon = location.coords.longitude;
document.getElementById("lat").innerHTML = myLat;
document.getElementById("lon").innerHTML = myLon;
$timeout(function() {
calculate();
});
}
$scope.getCoordDistance = function(myLat, myLon, locLat, locLon) {
var lat1 = locLat; //41.887055
var lon1 = locLon; //-88.469233
var lat2 = myLat; //41.888668
var lon2 = myLon; //-87.640371
var R = 3959;
var x1 = lat2 - lat1;
var dLat = x1 * Math.PI / 180;
var x2 = lon2 - lon1;
var dLon = x2 * Math.PI / 180;
a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
};
angular.forEach($scope.SSiteLocs, function(object) {
object.carrier = 'Sprint';
});
angular.forEach($scope.ASiteLocs, function(object) {
object.carrier = 'AT&T';
});
var i = 0;
locX = 1;
var calculate = function() {
angular.forEach($scope.SiteLocs, function(location) {
var clength = location.Point.coordinates.length;
if (location.Point.coordinates.substring(clength - 2, clength) === ",0") {
location.Point.coordinates = location.Point.coordinates.substring(0, clength - 2).split(",");
Lat = location.Point.coordinates[0];
Lon = location.Point.coordinates[1];
Com = ",";
location.Point.coordinates = Lon.concat(Com, Lat);
myLat = Number(document.getElementById("lat").innerHTML)
myLon = Number(document.getElementById("lon").innerHTML)
locLat = Lat;
locLon = Lon;
d = $scope.getCoordDistance(myLat, myLon, locLat, locLon);
location.distance = d.toFixed(1);
if(i < 15){
console.log("********LOCATON " + locX + "***********")
console.log("myCoords: " + myLat + "," + myLon);
console.log("locCoords: " + locLat + "," + locLon);
console.log("d: " + d);
console.log("***************************")
i++;
locX++;
}
}
});
};
});
The results from the formula are up to about 9-10 thousand when they should be no where near that high. If I use the commented out coordinates it returns correctly (42.6 Miles)
Since the test coordinates work I know it is not a math problem. Does anybody know what is causing the formula to not work correctly?
EDIT
Here is a plunker of the full proj. if that helps. EDIT2 I discovered something odd, the results are different in different browsers, so, chrome displays one set of numbers and IE displays another, ect.
Your point coordinates are longitude latitude
BRUSSELS",
"
"Point": {
"coordinates": "-90.58543899999999,38.955472
In your code
Lat = location.Point.coordinates[0];
Lon = location.Point.coordinates[1];
Either change them in your object(preferable) See Google latlng class
"Point": {
"coordinates": "38.955472,-90.58543899999999
or
Lat = location.Point.coordinates[1];
Lon = location.Point.coordinates[0];
With your settings distance is aprox 9000 miles with coordinates transposed distance is aprox 200
In addition to what kirinthos said in his response, you can easily test this by comparing your results with Google Maps. I have a function in my app that does this. The point1 and point2 parameters are simple Latlng objects.I wanted the results in kilometers so I divide by 1000.
function calculateDistanceBetweenTwoPoints(point1, point2) {
return (google.maps.geometry.spherical.computeDistanceBetween(point1, point2) / 1000).toFixed(2);
}
You'll need the following in your HTML page:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,places"></script>
I'm not entirely sure, here, without testing it but it looks like the GetLocation function is overwriting the closure scope of the variables myLat and myLon by declaring them as function arguments, so you're assigning the value of location.coords.latitude into the function scope myLat variable, instead of the myLat declared at the beginning of your code block.
throw a console.log(myLat, myLon); into the beginning of getCoordDistance and check their values. I'll bet they're not what you expect.
edit: it actually may have been the lack of semicolons and stuff. here's a small snippet of your code re-calibrated to run in an isolated environment like jsbin.com. It appears to work fine. you were missing 4 semicolons, so unless this assignment is failing, it should work: myLon = Number(document.getElementById("lon").innerHTML)
there were complaints of variable "i" and "locX" not being defined
var myLat, myLon;
var ASiteLocs = [{
"name": "IL5077 BRUSSELS",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.58543899999999,38.955472,0"
}
}, {
"name": "IL5076 KAMPSVILLE",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.661923,39.29403,0"
}
}, {
"name": "IL5146 CARROLLTON",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.39965700000001,39.309142,0"
}
}, {
"name": "IL5153 GREENFIELD",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.208747,39.364077,0"
}
}];
var SSiteLocs = [];
var SiteLocs = SSiteLocs.concat(ASiteLocs);
function GetLocation(location, myLat, myLon) {
myLat = location.coords.latitude;
myLon = location.coords.longitude;
document.getElementById("lat").innerHTML = myLat;
document.getElementById("lon").innerHTML = myLon;
}
function getCoordDistance(myLat, myLon, locLat, locLon) {
var lat1 = locLat; //41.887055
var lon1 = locLon; //-88.469233
var lat2 = myLat; //41.888668
var lon2 = myLon; //-87.640371
var R = 3959;
var x1 = lat2 - lat1;
var dLat = x1 * Math.PI / 180;
var x2 = lon2 - lon1;
var dLon = x2 * Math.PI / 180;
a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
};
function calculate() {
SiteLocs.forEach(function(location) {
var clength = location.Point.coordinates.length;
if (location.Point.coordinates.substring(clength - 2, clength) === ",0") {
location.Point.coordinates = location.Point.coordinates.substring(0, clength - 2).split(",");
Lat = location.Point.coordinates[0];
Lon = location.Point.coordinates[1];
Com = ",";
location.Point.coordinates = Lon.concat(Com, Lat);
myLat = -90.208747;
myLon = 39.364077;
locLat = Lat;
locLon = Lon;
d = getCoordDistance(myLat, myLon, locLat, locLon);
location.distance = d.toFixed(1);
//console.log("********LOCATON " + locX + "***********");
console.log("myCoords: " + myLat + "," + myLon);
console.log("locCoords: " + locLat + "," + locLon);
console.log("d: " + d);
console.log("***************************");
}
});
};

Haversine Formula and Geolocation in AngularJS

I'm, writing an app that'll sort location by either name or distance from the user. Everything works as it should except getting the distance. Theoretically, I should be able to get the coordinates of the user through geolocation and I already have the coordinates to every location. Shouldn't I be able to run the haversine formula with these coordinates and attach the distance to each location via object.distance = d? Here is my code and a plunk to my project.
Plunker: http://plnkr.co/edit/nRQc7Ym0lsaK6jQwd626?p=preview
Code:
var app = angular.module('app', []);
app.controller('firstCtrl', function($scope) {
$scope.ASiteLocs = [{
"name": "IL5077 BRUSSELS",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.58543899999999,38.955472,0"
}
}, {
"name": "IL5076 KAMPSVILLE",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.661923,39.29403,0"
}
}, {
"name": "IL5146 CARROLLTON",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.39965700000001,39.309142,0"
}
}, {
"name": "IL5153 GREENFIELD",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.208747,39.364077,0"
}
}];
$scope.SSiteLocs = [More Locations...];
$scope.SiteLocs = $scope.SSiteLocs.concat($scope.ASiteLocs);
repoSortOrder = "site.name";
navigator.geolocation.getCurrentPosition(GetLocation);
function GetLocation(location) {
Lat = location.coords.latitude;
Lon = location.coords.longitude;
}
angular.forEach($scope.SSiteLocs, function(object) {
object.carrier = 'Sprint';
getCoordDistance();
object.distance = $scope.d
});
angular.forEach($scope.ASiteLocs, function(object) {
object.carrier = 'AT&T';
getCoordDistance();
object.distance = $scope.d
});
angular.forEach($scope.SiteLocs, function(location) {
var clength = location.Point.coordinates.length;
if (location.Point.coordinates.substring(clength - 2, clength) === ",0") {
location.Point.coordinates = location.Point.coordinates.substring(0, clength - 2).split(",");
Lat = location.Point.coordinates[0];
Lon = location.Point.coordinates[1];
Com = ",";
location.Point.coordinates = Lon.concat(Com, Lat);
}
});
function getCoordDistance() {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
var lat2 = Lat;
var lon2 = Lon;
var lat1 = 45;//Test Lat
var lon1 = -50;//Test Lon
var R = 3959; // Radius in miles
//has a problem with the .toRad() method below.
var x1 = lat2 - lat1;
var dLat = x1.toRad();
var x2 = lon2 - lon1;
var dLon = x2.toRad();
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
$scope.d = R * c;
}
});
In the code above when I use integers for the Lat/Lons in getCoordDistance() for instance, lat1 = 5,lat2 = 10,lon1 = 0,lon2 = 0 it works and adds the distance to each location. But when I try to use my location it fails. Any Ideas? Thanks in advance for any help.
I figured it out, My getCoordDistance() was undefined.

Categories

Resources