This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Calculate “as the crow flies” distance php
I am trying to develop a GoogleMaps page where I can get the user location and show custom marker points from an XML file that fells within the calculated area around the user.
To make things more clear :
I have a radius parameter from WebConfig file, say 5000 (in meters)
I've found the user location on map,
Using the xml list that I own (xml has the Lat-Long values of
each store) I want to put custom markers on map which fell within
the 5 km^2 area range with the user's location as center.
Is there a way to achieve this goal?
How do I calculate a point's Lat & Long values by only passing user's location coordinates and a distance parameter (say 5000 in my case)?
Edit :
My XML doc is kinda huge including whitegoods stores all around the
country. My main problem is to filter these rows of data (long,latt)
using user's current location.
I need something like:
func distanceCale(int long, int latt, int radius)
to return me some values that can help me filter my XML data.
I guess my question was not clear enough at the firs place. :)
You can achieve this using the Haversine formula. This formula has been used in a Demo from an XML file showing markers within a given radius.
For your application the javascript code is used to generate markers from XML file.
function deg2rad(degrees){
radians = degrees * (Math.PI/180);
//document.write(radians);
return radians;
}
function Haversine(lat1,lon1,lat2,lon2) {
deltaLat = lat2 - lat1 ;
deltaLon = lon2 - lon1 ;
earthRadius = 3959; // in miles 6371 in meters.
alpha = deltaLat/2;
beta = deltaLon/2;
a = Math.sin(deg2rad(alpha)) * Math.sin(deg2rad(alpha)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(deg2rad(beta)) * Math.sin(deg2rad(beta)) ;
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
distance = earthRadius * c;
return distance.toFixed(2);
}
The Haversine function is used when parsing XML
var radius = document.getElementById('radiusSelect').value;
for (var i = 0; i < markerNodes.length; i++) {
var lat = parseFloat(markerNodes[i].getAttribute("lat"));
var lng = parseFloat(markerNodes[i].getAttribute("lng"));
var latlng = new google.maps.LatLng(
lat,
lng);
var distance = Haversine(center.lat(),center.lng(),lat,lng);
if(distance<=radius) {
createOption(name, distance, i);
createMarker(latlng, name, distance);
bounds.extend(latlng);
}
Related
New to GeoTools and GIS and I am trying to calculate distance between Mumbai and Durban using GeoTools library. I am getting close to accurate results for small distances but when i go for bigger ones,the calculation is way too offcourse by 2000 km, i dont completely understand the CRS system .Below is my Code to calculate the distance between Mumbai and Durban
Coordinate source = new Coordinate(19.0760, 72.8777); ///Mumbai Lat Long
Coordinate destination1 = new Coordinate(-29.883333, 31.049999); //Durban Lat Long
GeometryFactory geometryFactory = new GeometryFactory();
Geometry point1 = geometryFactory.createPoint(source);
Geometry point2 = geometryFactory.createPoint(destination1);
CoordinateReferenceSystem auto = auto = CRS.decode("AUTO:42001,13.45,52.3");
MathTransform transform = CRS.findMathTransform(DefaultGeographicCRS.WGS84, auto);
Geometry g3 = JTS.transform(point1, transform);
Geometry g4 = JTS.transform(point2, transform);
double distance = g3.distance(g4);
This is what happens when you copy code blindly from stackexchange questions without reading the question it was based on which explains why.
All the times I've answered that question (and posted code like that) the questioner is trying to use lat/lon coordinates in degrees to measure a short distance in metres. The trick shown in your question creates an automatic UTM projection centred on the position specified after the "AUTO:42001," bit (in your case 52N 13E) - this needs to be the centre of the area you are interested in, so in your case those values are probably wrong anyway.
But you aren't interested in a small region Mumbai to Durban is a significant way around the Earth so you need to allow for the curvature of the Earth's surface. Also you aren't trying to do something difficult for which JTS is the only source of process (e.g buffering). In this case you should use the GeodeticCalculator which takes the shape of the Earth into account using the library from C. F. F. Karney, Algorithms for geodesics, J. Geodesy 87, 43–55 (2013).
Anyway enough explanation that no one will read in the future, here's the code:
public static void main(String[] args) {
DefaultGeographicCRS crs = DefaultGeographicCRS.WGS84;
if (args.length != 4) {
System.err.println("Need 4 numbers lat_1 lon_1 lat_2 lon_2");
return;
}
GeometryFactory geomFactory = new GeometryFactory();
Point[] points = new Point[2];
for (int i = 0, k = 0; i < 2; i++, k += 2) {
double x = Double.valueOf(args[k]);
double y = Double.valueOf(args[k + 1]);
if (CRS.getAxisOrder(crs).equals(AxisOrder.NORTH_EAST)) {
System.out.println("working with a lat/lon crs");
points[i] = geomFactory.createPoint(new Coordinate(x, y));
} else {
System.out.println("working with a lon/lat crs");
points[i] = geomFactory.createPoint(new Coordinate(y, x));
}
}
double distance = 0.0;
GeodeticCalculator calc = new GeodeticCalculator(crs);
calc.setStartingGeographicPoint(points[0].getX(), points[0].getY());
calc.setDestinationGeographicPoint(points[1].getX(), points[1].getY());
distance = calc.getOrthodromicDistance();
double bearing = calc.getAzimuth();
Quantity<Length> dist = Quantities.getQuantity(distance, SI.METRE);
System.out.println(dist.to(MetricPrefix.KILO(SI.METRE)).getValue() + " Km");
System.out.println(dist.to(USCustomary.MILE).getValue() + " miles");
System.out.println("Bearing " + bearing + " degrees");
}
Giving:
working with a lon/lat crs
POINT (72.8777 19.076)
POINT (31.049999 -29.883333)
7032.866960793305 Km
4370.020928274692 miles
Bearing -139.53428618565218 degrees
I am trying to request an image from the Google Static Maps API with the borders of the map specified by a pair of latitude and longitude coordinates. I've tried centering on the center of the two coordinates, but there doesn't seem to be any parameter for doing this with the Static API. Does anyone know how to do this?
Note: this is for a desktop application, and I am not using the Javascript API.
The thing is that you cannot base the request on the map's corners because 1. zoom levels are discrete values and 2. the amount of latitude that a pixel represents varies with latitude. So, to display 2 degrees you'll need a given map height near the equator and a different height, (greater), near the poles. Are you willing to display maps of different heights in order to fit always 2 degrees?
If so, you can use the MercatorProjection object from my other post, and use the following function to calculate the necessary map size:
<script src="MercatorProjection.js"></script>
function getMapSize(center,zoom){
var proj = new MercatorProjection();
var scale = Math.pow(2,zoom);
var centerPx = proj.fromLatLngToPoint(center);
var SW = new google.maps.LatLng(center.lat()-1,center.lng()-1);
var southzWestPx = proj.fromLatLngToPoint(SW);
var NE = new google.maps.LatLng(center.lat()+1,center.lng()+1);
var northEastPx = proj.fromLatLngToPoint(NE);
// Then you can calculate the necessary width and height of the map:
var mapWidth = Math.round((northEastPx.x - southzWestPx.x) * scale);
var mapHeight = Math.round((southzWestPx.y - northEastPx.y) * scale);
}
With center = new google.maps.LatLng(49.141404, -121.960988) and zoom = 7 you get that you need a map of (W x H) 182 x 278 pixels in order to display 2 x 2 degrees.
I need to retrieve a destination's coordinates using the google maps api directions service. I already have the starting point coordinates, however instead of specifying an ending point in coordinates, I wish to retrieve the coordinates by specifying a distance (in km).
So I guess my question is the following: is it possible to retrieve the destination latlong coordinates (based/calculated on the road's distance and not directional/straight line) by specifying a distance (amount in km) with the directions service or perhaps any alternative way?
I have an image illustration, however unfortunately am unable to attach to this question as I do not have enough reputation. If my question is unclear in any way, or you wish to see the illustration then please contact me and I'll send it off.
I don't think you can do this as the request parameters say that origin and destination parameters are required.
I beliave it will help someone.
There is a method to get coordinates in the google maps library:
google.maps.geometry.spherical.computeOffset(fromCoordinates, distanceInMeters, headingInDegrees)
I believe you are correct. There doesn't seem to be any current method in the api which would allow you to do the following.
Instead I looped through the coordinates returned from the directions service call, and used a function to calculate the distance between coordinates. However even this was not accurate enough as the coordinates returned also seemed to be aggregated and doesn't return an accurate value/distance when calculating the distances between each coordinate as they are aggregated and therefore each coordinate is not necessary along the road.
To work around the above issue, I ended up adding a click event, and plotted the coordinates along the road myself and then stored them in a local json file which I cache and call using an xmlhttprequest.
Fortunately, for my situation I only need to calculate the distance between point A & B on one individual road, so my alternative won't work in cases when you're using multiple or generic roads/locations. You could instead use the first method described, given that you're happy to live with the aggregated data and an in-accurate calculation.
Below are the functions used to calculate the distances between coordinates and then also the final calculation to find the point & coordinates between the final two points. Please note this code relies on and uses jQuery methods.
1. Calculate distance (in meters) between two coordinates
function pointDistance( begin, end )
{
var begin = { lat: begin[0], long: begin[1] },
end = { lat: end[0], long: end[1] };
// General calculations
var earthRadius = 6371, //km
distanceLat = (end.lat - begin.lat).toRad(),
distanceLong = (end.long - begin.long).toRad();
// Convert lats to radiants
begin.lat = begin.lat.toRad();
end.lat = end.lat.toRad();
// Calculation
var a = Math.sin(distanceLat / 2) * Math.sin(distanceLat / 2) +
Math.sin(distanceLong / 2) * Math.sin(distanceLong / 2) * Math.cos(begin.lat) * Math.cos(end.lat);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var distance = (earthRadius * c) - 0.000536;
return (distance * 1000);
}
2. Fetch coordinate of final A-B coordinate (based on percentage remaining). The 'matrix' variable is a json array of coordinates.
function getCoordinates( totalDistance )
{
var lastPoint = { lat: null, long: null },
total = parseFloat(0),
position = { start: null, end: null, distance: 0 };
$(matrix).each(function()
{
if ( lastPoint.lat == null )
{
lastPoint = { lat: this[0], long: this[1] };
return;
}
var distance = pointDistance([lastPoint.lat, lastPoint.long], [this[0], this[1]]);
total = total + distance;
if ( (total / 1000) >= totalDistance )
{
position.start = new google.maps.LatLng(lastPoint.lat, lastPoint.long);
position.end = new google.maps.LatLng(this[0], this[1]);
position.distance = total;
return false;
}
lastPoint = { lat: this[0], long: this[1] };
});
return position;
}
3. Convert numeric degrees to radians
if ( typeof(Number.prototype.toRad) === 'undefined' ) {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
}
Hope the following helps any one with the same or simular problem. I haven't investigated this as I've had no need to, but, perhaps if you're dealing with google's paid services, they don't aggregate the data returned by the call?
I am using GStreetviewPanorama for one of my projects to show street view of a location. I want the values of parameters passed in GStreetviewPanorama method so that I can display the location exactly the way maps.google.com does (same camera orientation). I used :
latlngPoint is my GLatLng object here.
var panoramaOptions = { latlng: latlngPoint };
myPano = new GStreetviewPanorama(document.getElementById("strpano_div"), panoramaOptions);
I also tried
myPano = new GStreetviewPanorama(document.getElementById("strpano_div"));
var myPOV = {yaw:270};
myPano.setLocationAndPOV(latlngPoint,myPOV);
When i passed the address corresponding to above latlng in maps.google.com, the location is shown at a different angle. Please suggest me the best values for GPov options like : yaw,pitch and zoom so that camera orientation is exactly same as used by maps.google.com.
Thank you.
I have altered this code from the original, but I am sure that you can follow:
var panoPosLat = panoPos.lat() / 180 * Math.PI;
var panoPosLng = panoPos.lng() / 180 * Math.PI;
var y = Math.sin(markerPosLng - panoPosLng) * Math.cos(markerPosLat);
var x = Math.cos(panoPosLat)*Math.sin(markerPosLat) - Math.sin(panoPosLat)*Math.cos(markerPosLat)*Math.cos(markerPosLng - panoPosLng);
brng = Math.atan2(y, x) / Math.PI * 195;
var pov = mybigpano2.getPov();
pov.heading = parseFloat(brng);
mybigpano2.setPov(pov);
I use 195 degrees because there are many streets that have many curves.
Changing the heading is the key.
I think this is where I found the code:
enter link description here
I had some issues with originally and I posted here on stackoverflow:
enter link description here
Hope that helps
I need an algorithm that will convert a GPS coordinate to a screen location on a displayed google map. I would think this would be simple- get the coordinates for the four corners of the displayed map, find the differential and create a scaling factor for a pixel location on the screen. Is this correct or am I missing something. I'm know this has been done ad nauseum but I am hoping I can hear from someone who has implemented it successfully or has a resource for implementing it.
Basically you need the code for Transverse Mercator projection (which is used by Google maps and others). Here's a C# snippet I used my Kosmos software:
public Point2<int> ConvertMapToViewCoords (Point2<double> mapCoords)
{
double x = (mapCoords.X - MapPosition.Longitude) / resolution;
double y = Math.Log (Math.Tan (Math.PI*(0.25 + mapCoords.Y/360)))*u180dPiResolution;
return new Point2<int> ((int)(x + viewWidthHalf), (int)((y0 - y) + viewHeightHalf));
}
variables used:
double resolution = 360.0 / (Math.Pow (2, MapPosition.ZoomFactor) * 256);
double u180dPiResolution = 40.7436654315252 * Math.Pow(2, MapPosition.ZoomFactor);
double y0 = Math.Log(Math.Tan(Math.PI * (0.25 + MapPosition.Latitude / 360))) * u180dPiResolution;
float viewWidthHalf = ViewWidth / 2.0f;
float viewHeightHalf = ViewHeight / 2.0f;
ZoomFactor is Google zoom level (see http://laudontech.com/GISBlog/?p=28).
BTW the same code works for OpenStreetMap, Yahoo Maps etc., since they all use the same projection and tiling system.
The Google Maps API lets you do stuff like this.
Here is some JS code I've written using the APIs that does something similar:
var map = new GMap2(document.getElementById("map"));
//...
var location = new GLatLng(37.771008, -122.41175);
map.setCenter(location);
var marker = new GMarker(location);
var overlay_caption = "Our location!";
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(overlay_caption);
});
map.addOverlay(marker);
marker.openInfoWindowHtml(overlay_caption);
You can also redirect the page to a new map with a URL like this:
http://maps.google.com/maps?q=37.771008,+-122.41175+(You+can+insert+your+text+here)&iwloc=A&hl=en
If you need the pixel coordinate of a latitude/longitude position of a current instance of Google Maps you may use the fromLatLngToDivPixel() function.
Assuming map is an instance of an initialized GMap2:
var location = new GLatLng(37.771008, -122.41175);
var point = map.fromLatLngToDivPixel(location);
alert("X: " + point.x + ", Y: " + point.y);
Depending on your needs, see also fromLatLngToContainerPixel.