Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get user's location (latitude, longitude) with Bing or Google Maps API

is there a way to retrieve a latitude & longitude of the user using Bing Maps API or Google Maps API. I think I saw an code snippet where a "autolocate me" feature was used to mark user on the Map itself:

var geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map);  
geoLocationProvider.getCurrentPosition(); 

But that function doesn't return any data, it simply set location on the map, whereas I need that location to perform some calculations, namely calculate which of predefined list of places is the closest to current user location. Apart from that, does any of this API's can calculate the distance between two locations (lat,lon) that are provided as an input?

Thanks, Pawel

like image 339
dragonfly Avatar asked Jan 18 '12 17:01

dragonfly


People also ask

How do I get latitude and longitude from Google Maps API?

That's right, you can go straight to the simplest page on the Internet—google.com—and enter your latitude and longitude into the search box. Usually coordinates are listed with latitude first, then longitude. Double check that is the case and that you've included a comma between the numbers.

Is Bing Maps API free?

Developers can use the Basic Key for building location intelligence-based apps with Bing Maps API for free. Educational institutions and non-profits are also free to build with the Basic Key.


1 Answers

Getting your location isn't part of the Map API. Instead, use the HTML5 GeoLocation API to get your location. An example would be:

 navigator.geolocation.getCurrentPosition(locationHandler);

 function locationHandler(position)
 {
   var lat = position.coords.latitude;
   var lng = position.coords.longitude;
 }

For calculating distance between lat/lng points, have a look at http://www.movable-type.co.uk/scripts/latlong.html.

// Latitude/longitude spherical geodesy formulae & scripts (c) Chris Veness 2002-2011                   - www.movable-type.co.uk/scripts/latlong.html 
// where R is earth’s radius (mean radius = 6,371km);
// note that angles need to be in radians to pass to trig functions!
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();

var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c;
like image 99
Kevin Avatar answered Oct 18 '22 05:10

Kevin