I am writing an online map using google maps API (vs3).

What I am doing is storing locations (lat and long) on my database and adding them to the map on initialize() - which places markers depending on their position. So far so good.

Now I have a function which shows my position (or a position defined by the user). I would like to show the places which are within 111 km = 1 degree lat/lng. How can I do that?

Just to show you what i mean :

function showPlaceCloseBy(lat,lng){

var myLat=lat;
var myLng=lng;

for (var i=0; i < pins.length; i++) {
     // HERE WE FIND WHETHER THE PLACE IS CLOSE ENOUGH
             returnDistance(myLat, myLng, pins[i],i);

    }
}



function returnDistance(myLat,myLng,pinToCompare,i){

// PIN  
var calcLat= myLat-pinToCompare.position.hb; // IS THIS RIGHT?
var calcLong = myLng-pinToCompare.position.ib; // IS THIS RIGHT?

 // HERE I NEED TO DO THE CALCULATION AND RETURN THE PIN NAME.              

     }

So, now I need to make a calculation (probably a subtraction - ? -) between the myLat and the pinLat. Can anyone help me?

Thank to you all.

有帮助吗?

解决方案

The Google Maps API v3 spherical geometry library has a method:

computeDistanceBetween(from:LatLng, to:LatLng) - number - Returns the distance between two LatLngs.

Which returns the distance between two LatLng objects in meters.

(not tested)

var closeDistance = 111000; // 111 km
function showPlaceCloseBy(lat,lng){
  var myLocation = new google.maps.LatLng(lat, lng);
  closePins = [];
  for (var i=0; i < pins.length; i++) {
     // HERE WE FIND WHETHER THE PLACE IS CLOSE ENOUGH
     if (calculateDistanceBetween(myLocation, pins[i].getPosition()) < closeDistance)
     {
       closePins.push(pins[i]);
     }
  }
  return closePins;
}


// Note: do not use undocumented properties like .hb, .ib; they can and do change.
var calcLat= myLat-pinToCompare.position.hb; // IS THIS RIGHT?
var calcLong = myLng-pinToCompare.position.ib; // IS THIS RIGHT?

其他提示

This should be just a simple distance calculation http://www.purplemath.com/modules/distform.htm

so your code would be

return Math.sqrt( Math.pow( calcLat, 2 ) + Math.pow( calcLong, 2 ) )

You will find everything here: http://www.movable-type.co.uk/scripts/latlong.html

Distance with various accuracy, direction (bearing/azimuth), everything ;-)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top