2

I have a list of lat longs using that I need to find nearest one to a position (lat,long).

I do not want to use any formula because it will take lot of time on calculations. Is there any way in which I can use google api or I an upload My list to any google account where I just hit with my current location and it will return with nearest one place and distance?

Gourav Soni
  • 75
  • 2
  • 11

2 Answers2

1

Yes. first you have to load the geometry library

<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script><script>

Then you can use the Google maps function google.maps.geometry.spherical.computeDistanceBetween

You put the results in a for-loop, or in an array; then you return the minimal result.

Here is a web example of your question

<style>
  #map {
    height: 400px;
  }
</style>

<div id="map"></div>
<input type="button" value="Minimal Distance" onclick="displayMinimalDistance()">
<div id="log"></div>

<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script><script>
var myLocations = [
  {lat: 50.0,lng: 4.5},
  {lat: 50.1,lng: 4.7},
  {lat: 50.4,lng: 4.8},
  {lat: 50.7,lng: 4.9},
  {lat: 50.2,lng: 4.4},
  {lat: 50.5,lng: 4.0},
  {lat: 50.8,lng: 4.6},
  {lat: 50.3,lng: 4.1},
  {lat: 50.6,lng: 4.2},
  {lat: 50.9,lng: 4.3}
];
var myLocation =  {lat: 50.5,lng: 4.5};

// Google maps stuff
function initialize() {
  var markers = [];
  var myMarker;
  var mapCenter = new google.maps.LatLng(50.5, 4.5);
  var myOptions = {
    zoom: 8,
    center: mapCenter,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map"), myOptions);
  addMarkers();

  // adding the markers
  function addMarkers() {
    for(i in myLocations) {
      markers.push(new google.maps.Marker({
          position:  new google.maps.LatLng(myLocations[i].lat, myLocations[i].lng),
          title: i,
          map: map
        })
      );
    }
    var myMarker = new google.maps.Marker({
      position:  new google.maps.LatLng(myLocation.lat, myLocation.lng),
      title: 'You are here',
      icon: {
        url: 'http://www.euroheat.co.uk/images/you-are-here-icon.png', 
        size: new google.maps.Size(48, 48),
        origin: new google.maps.Point(0,0),
        anchor: new google.maps.Point(24,42)
      },
      map: map
    });
  } 
}
google.maps.event.addDomListener(window, 'load', initialize);

// distance stuff
// returns an object: {i: 'key of the location', dist: 'distance'}
function getMinimalDistance(location, locations) {
  var minDistance = 20000000; // and now we will look for any shorter distance
  var minDistanceKey = -1;
  var dist;
  for(i in locations) {
    dist = getDistance(location, locations[i]);
    if(dist < minDistance) {
      minDistance = dist;
      minDistanceKey = i;
    }
  }
  return {i: minDistanceKey, dist: minDistance};
}
function getDistance(source, destination) {
  return google.maps.geometry.spherical.computeDistanceBetween(
    new google.maps.LatLng(source.lat, source.lng),
    new google.maps.LatLng(destination.lat, destination.lng)
  );
}
// writes down the result of getMinimalDistance to a log div
function displayMinimalDistance() {
  var minDistance = getMinimalDistance(myLocation, myLocations);
  document.getElementById('log').innerHTML = 
    'Key of the marker at minimal distance: ' + minDistance.i 
    + ' - distance: ' + minDistance.dist; 
}
</script>
Emmanuel Delay
  • 3,619
  • 1
  • 11
  • 17
  • I didn't wanted to use for loop for this . I mean is it possible that I uplod all my locations in some google platform and at the time of request I will just pass lat long or area name and it will provide me nearest one ? – Gourav Soni Sep 27 '15 at 07:24
-1

you can also refer this question SQL Distance Query without Trigonometry there is where i found inspiration for this function

    protected void findClosestResources(LatLng mCurrentLocation, GoogleMap map,Context context){
            Double currentLatitude=mCurrentLocation.latitude;
            Double currentLongitude=mCurrentLocation.longitude;
            Double longitudeDifferenceCorrection=1/Math.cos(currentLatitude);
            Location=Place.query(LOCATION_TABLE_NAME, M_COLUMNS, "MIN(("+M_COLUMNS[1]+" - "+currentLatitude+") * ("+M_COLUMNS[1]+" - "+currentLatitude+
                    ") + (("+M_COLUMNS[2]+" - "+currentLongitude+") * "+longitudeDifferenceCorrection+
                    ") * (("+M_COLUMNS[2]+" - "+currentLongitude+") * "+longitudeDifferenceCorrection+"))", null,null
                    , null, null);
if (Location.moveToFirst()) {//select the first row in the cursor object
            getInformationAbout(Location);
            PlaceMakerOn(map);
            Location.close();//close the connection with database
        }

this function find the closest location by selecting them from the list of lat lon saved in a SQLite database

using Location=Place.query(LOCATION_TABLE_NAME, M_COLUMNS, "MIN(("+M_COLUMNS[1]+" - "+currentLatitude+") * ("+M_COLUMNS[1]+" - "+currentLatitude+ ") + (("+M_COLUMNS[2]+" - "+currentLongitude+") * "+longitudeDifferenceCorrection+ ") * (("+M_COLUMNS[2]+" - "+currentLongitude+") * "+longitudeDifferenceCorrection+"))", null,null , null, null); where MIN(("+M_COLUMNS[1]+" - "+currentLatitude+") * ("+M_COLUMNS[1]+" - "+currentLatitude+ ") + (("+M_COLUMNS[2]+" - "+currentLongitude+") * "+longitudeDifferenceCorrection+ ") * (("+M_COLUMNS[2]+" - "+currentLongitude+") * "+longitudeDifferenceCorrection+"))" is the WHERE clausule for the SQLite statement and where M_COLUMNS[1] and M_COLUMNS[2]are the columns in the database for latitude and longitude repectively by squaring the difference between the latitudes and longitudes of both the locations from the db and the current location the error resulting from this method is reduced while multiplying the squared value of the longitude difference with longitudeDifferenceCorrection does just as the name implies

Community
  • 1
  • 1
Fuseteam
  • 376
  • 2
  • 15