How to find distance between two points using google maps geometry library? - javascript

I have attached the library
<script type="text/javascript" src="http://maps.googleapis.com`/maps/api/js?libraries=geometry&sensor=false"></script>
I have place A, with Latitude 30.694491 and longitude 76.665095
and place B with Latitude 30.7141289 and longitude 76.709398
<script>
computeDistanceBetween(from:LatLng, to:LatLng, radius?:number);
</script>
i dont know how to add lat and long to above function???
i want the distance between 2 places!!!!
and also is it possible to find displacement between them????

Use google.maps.geometry.spherical.computeDistanceBetween(a,b) to find distance between two points... read about computeDistanceBetween
It's in meters
var a = new google.maps.LatLng(30.694491, 76.665095);
var b = new google.maps.LatLng(30.7141289, 76.709398);
console.log(google.maps.geometry.spherical.computeDistanceBetween(a,b));
alert(google.maps.geometry.spherical.computeDistanceBetween(a,b));
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry&sensor=false&language=en"></script>

You need to create LatLng Objects.
var _aCord = new google.maps.LatLng(30.694491, 30.694491);
var _bCord = new google.maps.LatLng(30.7141289, 76.709398);
computeDistanceBetween(_aCord, _bCord);

Related

Convert X,Y pixel to Longitude and Latitude

I have an image 8640x11520 pixels from a part of the map in real scale. I need convert my x, y point to coordinate, anyone has an idea to find out it??
var mapWidth = 8640;
var mapHeight = 11520;
var mapLatitudeStart = 28.349768989955244;
var mapLongitudeStart = -81.55803680419922;
var maxLatitude = 28.349806758250104;
var maxLongitude = -81.541128;
var pointNeedConversion = {'x': 4813.10 'y': 2674.84};
var pointLatitude = ??
As you are mapping to lat/long, beware, you can't do that with a linear proportion, instead you have to check what kind of projection is applied to the map, then convert coordinates accordingly.
Usually maps are WGS84 Projections so you have to apply the inverse formulas for the Mercator projection.
The task is not trivial so my advice is to rely on libraries like Proj4js
The usage of the library is simple, you provide a reference system to work on, then you can trasform coordinates on another projection.
// include the library
<script src="lib/proj4js-combined.js"></script> //adjust the path for your server
//or else use the compressed version
// creating source and destination Proj4js objects
// once initialized, these may be re-used as often as needed
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/
// transforming point coordinates
var p = new Proj4js.Point(-76.0,45.0); //any object will do as long as it has 'x' and 'y' properties
Proj4js.transform(source, dest, p); //do the transformation. x and y are modified in place
//p.x and p.y are now EPSG:3785 in meters
Credit for the snippet: Convert long/lat to pixel x/y on a given picture
Working example:
var dest = new proj4.Proj('EPSG:4326'); //destination coordinates coordinates will be in Longitude/Latitude, WGS84 , global spherical mercators projection, see http://spatialreference.org/ref/epsg/3785/
var source = new proj4.Proj('EPSG:3785'); //source coordinates in meters
$("#convert").on("click", function(){
var p = new proj4.Point($("#x").val(), $("#y").val() );
proj4.transform(source, dest, p);
alert("lng : " +p.x + " \nlat : " + p.y);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.3/proj4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
x : <input type="number" id="x" />
y : <input type="number" id="y" />
<button id="convert">Convert</button>
Note: it is essential to know what is the lat/lon of the corner of your map if you intend to use it to map a GPS signal.
Here a graph example that visually explains why a linear proportion is not suitable:
Take a close look to (Eg) the size of the Greenland, on mercator projection space coordinates it looks bigger than north America. Of course it is not!

Get route length inside country

Could you suggest any idea how to do the following task?
I have the route from point A to point B. The route passes through several countries. How Can I calculate using Google Maps or alternative the distance of route part for each country?
Will be very appreciated for any ideas?
This should get you going, check fiddle here https://jsfiddle.net/yeoman/nm50vypx/1/
Basically do following:
1. Get latitude and longitude of FIRST point
2. Get latitude and longitude of SECOND point
3. User built-in API function google.maps.geometry.spherical.computeDistanceBetween()
var p1 = new google.maps.LatLng(45.463688, 9.18814);
var p2 = new google.maps.LatLng(46.0438317, 9.75936230000002);
alert(calcDistance(p1, p2));
//calculates distance between two points in km's
function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
IMPORTANT: your script tag must have &libraries=geometry included in it.
For example <script type="text/javascript" src="http://maps.google.com/maps/api/js?key=YOURKEYHERE&libraries=geometry"></script>
Another One line example
var latitude1 = 39.46;
var longitude1 = -0.36;
var latitude2 = 40.40;
var longitude2 = -3.68;
var distance = google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(latitude1,longitude1), new google.maps.LatLng(latitude2,longitude2));
EDIT: Distance results are expressed in meters

center of a polygon created with mapbox

I would like to know how to calculate the centre of a polygon created with this code from Mapbox: https://www.mapbox.com/mapbox.js/example/v1.0.0/show-polygon-area/
I would like to place a marker on the centre of the polygon after it's been created.
Thanks in advance.
To calculate the center of a polygon you first need to get it's bounds, that can be done using the getBounds method of L.Polygon which it enherits from L.Polyline:
Returns the LatLngBounds of the polyline.
http://leafletjs.com/reference.html#polyline-getbounds
It returns a L.LatLngBounds object which has a getCenter method:
Returns the center point of the bounds
http://leafletjs.com/reference.html#latlngbounds-getcenter
It returns a L.LatLng object which you can use to create a L.Marker:
var polygon = new L.Polygon(coordinates).addTo(map);
var bounds = polygon.getBounds();
var center = bounds.getCenter();
var marker = new L.Marker(center).addTo(map);
Or you can shorthand it:
var polygon = new L.Polygon(coordinates).addTo(map);
var marker = new L.Marker(polygon.getBounds().getCenter()).addTo(map);
Using that in the Mapbox example would look something like this:
function showPolygonArea(e) {
featureGroup.clearLayers();
featureGroup.addLayer(e.layer);
// Here 'e.layer' holds the L.Polygon instance:
new L.Marker(e.layer.getBounds().getCenter()).addTo(featureGroup);
e.layer.bindPopup((LGeo.area(e.layer) / 1000000).toFixed(2) + ' km<sup>2</sup>');
e.layer.openPopup();
}
You can use turf library.turf.center(features) gives you a point feature at the absolute center point of all input features. where features in your case will be the polygon selected which you can get using mapboxDraw.getAll()

OpenStreetMap point not showing on map with open layers

var map;
var vectors;
var point;
var drag;
Any long and Lat can be used
function mapCreate(lon,lat){
map = new OpenLayers.Map("map1");
var osm = new OpenLayers.Layer.OSM();
//create a vector
vectors = new OpenLayers.Layer.Vector("Vector Layer");
map.addLayer(osm);
var center = new OpenLayers.LonLat(lon,lat).transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
);
Assign a lat long to the point
point = new OpenLayers.Geometry.Point(lat,lon);
Add point to vectors
vectors.addFeatures([new OpenLayers.Feature.Vector(point)]);
map.setCenter(center, 15);
//add vectors to map
map.addLayer(vectors);
}
Am I missing something?
Are you looking at the full map? There's a high chance that you're setting the point's location as lat/lon. The OpenLayers LonLat object is so named only to trick innocent users like you into thinking that it automatically converts latitude longitude, or expects them, or something. Don't trust it, reproject into the projection of your map.
I thought Collection were necessary, but looks like you have lat & lon swapped. A point must have lon, then lat.
feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Collection([new OpenLayers.Geometry.Point(0, 0)]), {});
vectors.addFeatures([feature]);

google maps middle of a polyline (centroid?)

I have a list of polylines, just like google maps does when I click on the polyline I want an infowindow to show up just where I clicked, and it works just fine with this function
function mapsInfoWindow(polyline, content) {
google.maps.event.addListener(polyline, 'click', function(event) {
infowindow.content = content;
infowindow.position = event.latLng;
infowindow.open(map);
});
}
the problem comes when I click on the list(using the same function for that), event obviously doesn't have the latLng, but I'd like infowindow to show up in the middle of the polyline anyway, just like it does when you click on the list in the google maps link I mentioned before.
Tried LatLngBounds(); but that gives the actuall center of the area the polylines create, not the middle I need.
Any idea how to do it?
So this is the(bit hacky) solution.
Use http://www.geocodezip.com/scripts/v3_epoly.js library, then count the total length of you polyline(various ways), divide it in half and call epoly's .GetPointsAtDistance() function upon it.
This should return LatLng point, but it acts a bit weird sometimes, returning two points or even turning that point somehow "broken". So the most secure thing you can do is probably this:
var pointInHalf = polyline.GetPointsAtDistance(polylineLength);
var pointCoordinate = new google.maps.LatLng(pointInHalf[0].lat(), pointInHalf[0].lng());
Well, better than nothing.
From http://www.geocodezip.com/v3_polyline_example_geodesic_proj.html
Without extensions and assuming the polyline is a straight line.
It is possible to convert the lat/lng coordinates to point plane (x,y) postions and calculate the average between the two. This will give you a central pixel position. You can then convert this position back to a latlng for map plotting.
var startLatLng = startMarker.getPosition();
var endLatLng = endMarker.getPosition();
var startPoint = projection.fromLatLngToPoint(startLatLng);
var endPoint = projection.fromLatLngToPoint(endLatLng);
// Average
var midPoint = new google.maps.Point(
(startPoint.x + endPoint.x) / 2,
(startPoint.y + endPoint.y) / 2);
// Unproject
var midLatLng = projection.fromPointToLatLng(midPoint);
var midMarker = createMarker(midLatLng, "text");
More information on changing the projection http://code.google.com/apis/maps/documentation/javascript/reference.html#Projection
So firstly you need to use the geometry library which calculates distances. Add libraries=geometry to your JS call, e.g.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
Assuming you know the start point and end point for your polyline, you should be able to do this:
var inBetween = google.maps.geometry.spherical.interpolate(startLatlng, endLatlng, 0.5);
infowindow.position = inBetween;
I guess if you don't already know the start and end points, you could work it out from polyline.getPath().
to get the coordinates of your polyline you should do:
var widePath = new google.maps.Polyline({
path: waypointsCoordinates,
strokeColor: '#3366FF',
strokeOpacity: 0.0,
editable: true,
draggable: true,
strokeWeight: 3
});
and do:
var latLng [];
latLng = widePath.getPath().getArray();
Might be a bit old as well, but why not add the infobox on the click?
infowindow.setPosition(event.latLng);
infowindow.open(this.getMap());
If it's a click that is.

Categories

Resources