OpenLayers 2: Unexpected results from Point.distanceTo() - javascript

I try to use OpenLayers 2 to calculate the distance between Points of a GPS track. I tried using Point.distanceTo(), with just the points, and with the points transformed to my map. In both cases I get a result I can't really interpret:
var epsg4326 = new OpenLayers.Projection("EPSG:4326");
var pointA = new OpenLayers.Geometry.Point(5.339911, 60.371876);
var pointB= new OpenLayers.Geometry.Point(5.34003, 60.371471);
console.log("raw: " + pointA.distanceTo(pointB));
pointA = new OpenLayers.Geometry.Point(5.339911, 60.371876).transform(epsg4326, this.map.getProjectionObject());
pointB= new OpenLayers.Geometry.Point(5.34003, 60.371471).transform(epsg4326, this.map.getProjectionObject());
console.log("transformed: " + PointA.distanceTo(pointB));
gives the following output:
raw: 0.0004221208357810271
transformed: 92.1524487013366
According to http://www.movable-type.co.uk/scripts/latlong.html the result should be 45.51 m, which is consistent with my expectations.
Am I doing something wrong, or is the result in a unit I'm not expecting?

Try
var line = new OpenLayers.Geometry.LineString([pointA, pointB]);
console.log("Distance: " +line.getGeodesicLength(epsg4326));
this gives you 45,6 (Google Maps gives 46m)
-distanceTo wroks with planar measure (earth is not falt :D)
Calculate the closest distance between two geometries (on the x-y plane).
http://dev.openlayers.org/docs/files/OpenLayers/Geometry-js.html#OpenLayers.Geometry.distanceTo
Hope this helps

Related

Convert Long And Lat to X Y coordinate using ArcGis Api For Javascript

Hello i'm trying to convert long,lat values to X,Y using ArcGis Api For Javascript
var i = esri.geometry.lngLatToXY(3.13, 36.742)
console.log(i); //returns Array [ 348541.32567373366, 4403205.668961807 ]
in what system does this conversion take place?
is there a method to specify the projection system?
note: the conversion is done from decimal degree to meters
i followed this :
https://developers.arcgis.com/javascript/3/jsapi/esri.geometry.webmercatorutils-amd.html
This method is used to convert geographic coordinate system longitude/latitude (wkid 4326) to projected coordinate system Web Mercator (wkid 102100).
Default esri map use Web Mercator as projection system. If you need to convert your coordinates to an other coordinate system you need to use the project method of GeometryService :
https://developers.arcgis.com/javascript/3/jsapi/geometryservice-amd.html
Example:
require(["esri/geometry/Point", "esri/tasks/GeometryService", "esri/tasks/ProjectParameters", "esri/SpatialReference", "dojo/domReady!"],
function(Point, GeometryService, ProjectParameters, SpatialReference) {
var outSR = "YOUR_OUTPUT_COORDINATE_SYSTEM"; // `wkid {number}`
var geometryService = new GeometryService("https://utility.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
var inputpoint = new Point({
longitude: "YOUR_LONGITUDE_INPUT",
latitude: "YOUR_LATITUDE_INPUT"
});
var projectParams = new ProjectParameters();
projectParams.geometries = [inputpoint];
projectParams.outSR = new SpatialReference({ wkid: outSR });
geometryService.project(projectParams, (result) => {
let outputpoint = result[0]; // outputpoint first element of result array
console.log("Result x:", outputpoint.x, "y :", outputpoint.y);
});
});
Wkid numbers can be found here:
projected coordinate system: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Projected_coordinate_systems/02r3000000vt000000/
Geographic coordinate system: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Geographic_coordinate_systems/02r300000105000000/
EDIT
Here is a working example: Plunker

Getting the left-center or right-center point on a Google Maps map

Currently I can retrieve the center point of the map using
new google.maps.LatLng(map.getCenter().lat(), map.getCenter().lng());
What I am now trying to do, is get the left-center OR the right-center point of the map. For example:
Link to example image
As far as I know, there is no built in Google Maps API function to retrieve either of these points.
You can get the bound
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
then get the middle of the lats and lngs
eg in Nothern - Western area (otherwise check for min and max lat and lng):
middleLat = sw.lat() + ( ne.lat() - sw.lat())/2;
your left center is in
(middleLat, sw.lng() )
you right center is in
(middleLat, ne.lng() )

Create a map with coordinates-based marker using Javascript, jQuery and/or php

I am developing a client-server application and I need to create or obtain a geographical map with some markers (just red points, for example) on it based on lat and lang.
I have been looking on the web but I couldn't find anything ok for me.
I could do it using google maps but I think I can't use my own custom map-image and my custom markers.
However, this is an example of what I'd like to do more or less having some coordinates:
http://www.morrisda.com/?post=pointmap
Here explanation of how i managed this. With example !
Here source code:
function make_pointers(latitude, longitude) {
targetmap = document.getElementById("point_map");
//it's sure it will work when your map is a perfec square, so it's got height on the x and on the y for usefull debugging.
var asseX = $('#point_map').height()
var asseY = $('#point_map').height()
//lat and lang from imput
lang = longitude;
lat = latitude;
var source = new Proj4js.Proj('EPSG:4326'); //source coordinates will be in Longitude/Latitude, WGS84
var dest = new Proj4js.Proj('EPSG:3785'); //destination coordinates in meters, global spherical mercators projection, see http://spatialreference.org/ref/epsg/3785/
var mercator_object = new Proj4js.Point(lang,lat); //any object will do as long as it has 'x' and 'y' properties
Proj4js.transform(source, dest, mercator_object);
give_top = 19971868.8804*2 //this is how a meridian is long.
mercator_longitude = mercator_object.y //this is longitude by mercator
//this switch is if latitude is negative;
if (mercator_object.y > 0) {mercator_object.y = mercator_object.y + give_top/2}
if (mercator_object.y < 0 ) {mercator_object.y = give_top/2 + mercator_object.y}
//this is my lovely proportion, value of give_top is length of a meridian
mercator_distance = (asseY*mercator_longitude)/give_top;
//distance from 0:
y = asseY/2 - mercator_distance;
//proportion to make working on x;
//(180 + lang) makes lang from 0 to 360 instead of -180, +180.
//to understand, now image equator as a line, long 360.
//now we divide our coords (from 0 to 360) for 360, and the result is how far is this point from 0 on a 360-long line.
//now a simple proportion, and we get this distance on a line long like x axis, which is the width of our map.
// % is a Modulus (division remainder)
normalized_x_coords = (180 + lang)
x = (asseX * normalized_x_coords/ 360) % asseX;
//let's put this little points on my map (subtract -3 cause our point is large 6.)
console.log(x); //this is distance from left border;
console.log(y) //this is distance from bottom border
}
Remember you need jQuery and ProJ4js to use this. More info in previous link
Have a look at Slippy Map On Canvas project that is a implemenation of a slippy tiles map using HTML5. You can configure your own map and markers, and it also supports many other features which may be useful for you.

Translating math equation into JS

im trying to see if this
Math.sqrt(
Math.pow((position.coords.latitude -45),2) +
Math.pow((position.coords.longitude-75),2)
)*79;
Matches this:
Distance to store (km) = Square Root (
(Current Latitude – 45)^2 +
(Current Longitude ‐75)^2
) *79
Right now im getting 11,XXX KM which is way to much, but I don't see any mistakes.
I also tried doing it like this:
var x = Math.pow((position.coords.latitude-45),2);
var y = Math.pow((position.coords.longitude-75),2);
var z = Math.sqrt(x+y);
var zz = z*79;
but it gave me the same answer.
This formula is valid for short distances to the point of latitude 45 and longitude 75.
What you want, as you're not located in Kazakstan, is the distance to (45, -75), that is
Math.sqrt(Math.pow((lat-45),2)+Math.pow((lon+75),2))*79;
^
Note that it's only as precise as your coordinates are precise and that for bigger distances you should grab a better formula.

Drawing irregular concentric circles using Google Maps

I have a bit of a problem. I am trying to do the following using Javascript & the Google Maps API v2:
I can draw individual circles just fine using formulas found all over the Internet. The problem I am facing is that the circles must:
A. Be concentric, and
B. Must have different radius for each "quadrant", i.e., NE, NW, SE & SW
I've searched almost everywhere I can think of on the Internet, and have come up with no way on how to do this. Clearly someone has done this before, and thus why I'm asking in a forum of programmers. :)
Thanks!
UPDATE: I have drawn out, using the following code, what I think the coordinates for each of the points would be. for the drawing below:
This was obtained using the following JS:
http://gist.github.com/181290
NOTE: This javascript is from (slightly modified) the following site, which may hold more answers in terms of what the algorithm may end up being: http://www.movable-type.co.uk/scripts/latlong.html
UPDATE 2: I was able to get this in Google Maps:
Created using the following code:
var NEQ = [0, 90];
var SEQ = [90, 180];
var SWQ = [180, 270];
var NWQ = [270, 0];
// var centrePoint = new LatLon(25.0, -83.1);
// pointsForWindQuadrant(NEQ, centrePoint, 50);
function pointsForWindQuadrant(quadrantDegrees, centrePoint, radius){
var points = [];
// Points must be pushed into the array in order
points.push(new google.maps.LatLng(centrePoint.lat, centrePoint.lon));
for(i = quadrantDegrees[0]; i <= quadrantDegrees[1]; i++){
var point = centrePoint.destPoint(i, radius * 1.85);
points.push(new google.maps.LatLng(point.lat, point.lon)); // Radius should be in nautical miles from NHC
}
points.push(new google.maps.LatLng(centrePoint.lat, centrePoint.lon));
return points;
}
UPDATE 3: I should probably also point out that this is for a geographic coordinate system (as this whole thing is for tropical cyclone wind radii), not the Cartesian coordinate system. Thanks!
Basically, calculate the circle as the x,y = (cos(a), sin(a)), and then multiple this (both terms) by a radius that's the appropriate function of the angle. I don't know Javascript well, or Google maps, so I'll do this in Python, hopefully it's clear enough from this.
from pylab import *
def Rscale(a):
if a>3*pi/2: # lower right, and then work CW around the circle
return 1.
elif a>pi: # lower left
return .9
elif a>pi/2: # upper left
return .8
else: # upper right
return 1.
def step_circle(R):
return array([(R*Rscale(a))*array([cos(a), sin(a)]) for a in arange(0, 2*pi, .001)])
for R in (.5, .7, .9): # make three concentric circles
c = step_circle(R)
plot(c[:,0], c[:,1])
show()
Which gives
I couldn't really follow your sketch, so I just guessed at the numbers. Also, I made the two rightmost quadrants to be the same since that's what your plot looked like, but that is, of course, optional.
I figured it out. Here is the final code. Maybe it can be refactored a bit?
// Returns points for a wind field for a cyclone. Requires
// a LatLon centre point, and an array of wind radii, starting
// from the northeast quadrant (NEQ), i.e., [200, 200, 150, 175]
//
// Returns points to be used in a GPolyline object.
function pointsForWindQuadrant(centrePoint, radii){
if(radii.length != 4){ return false; }
var points = [];
var angles = [0, 90, 180, 270];
// For each angle 0, 90, 180, 270...
for(a = 0; a < angles.length; a++){
// For each individual angle within the range, create a point...
for(i = angles[a]; i <= angles[a] + 90; i++){
var point = centrePoint.destPoint(i, radii[a] * 1.85); // Radius should be in nautical miles from NHC
points.push(new google.maps.LatLng(point.lat, point.lon));
}
}
// Add the first point again, to be able to close the GPolyline
var point = centrePoint.destPoint(0, radii[0] * 1.85);
points.push(new google.maps.LatLng(point.lat, point.lon));
return points;
}
This results in the following:

Categories