2012-04-24 25 views

Respuesta

16

Sólo recorrer todos los marcadores que tenga y utilice la siguiente función para obtener la distancia desde la coordenada específica para el marcador: computeDistanceBetween():

Para calcular esta distancia, llame computeDistanceBetween(), pasándole dos objetos LatLng.

Lo encontré más de here. Luego filtra todos los marcadores que estén lo suficientemente cerca.

+0

Sí que trabajaron muchas gracias !! –

-1

Ver la respuesta a esta pregunta: Google Maps Api v3 - find nearest markers

Usted necesita básicamente colocar a través de la matriz de marcadores, y utilizar una fórmula para calcular la distancia de un punto dado (el centro del círculo que representa su radio de búsqueda)

Puede excluir cualquier marcador que esté más alejado que el radio, y le dejará una lista de marcadores dentro del círculo.

5
var targetLat=marker.getPosition().lat(); 
var targetLng=marker.getPosition().lng(); 

var targetLoc = new GLatLng(targetLat,targetLng); 

var center= new GLatLng(centerLat, centerLng); 

var distanceInkm=center.distanceFrom(targetLoc)/1000; 

if(distanceInkm < radius){ 
// To add the marker to the map, call setMap(); 
marker.setMap(map); 
} 
+0

'GLatLng' está en desuso en V3, se llama' google.maps.LatLng' ahora – Faloude

1

Aquí hay un ejemplo de trabajo. Haga clic en el mapa para dibujar un radio con el radio seleccionado y se mostrarán todos los marcadores del array de ejemplo all_locations que caen dentro del radio. Haga clic en un marcador para ver la distancia en metros desde el centro del radio. (Haga clic en algún lugar alrededor de la Second Street de Nueva York para ver los marcadores ejemplo - mapa ya está centrada en esa ubicación)

var map = null; 
 
    var radius_circle = null; 
 
    var markers_on_map = []; 
 
    
 
    //all_locations is just a sample, you will probably load those from database 
 
    var all_locations = [ 
 
\t {type: "Restaurant", name: "Restaurant 1", lat: 40.723080, lng: -73.984340}, 
 
\t {type: "School", name: "School 1", lat: 40.724705, lng: -73.986611}, 
 
\t {type: "School", name: "School 2", lat: 40.724165, lng: -73.983883}, 
 
\t {type: "Restaurant", name: "Restaurant 2", lat: 40.721819, lng: -73.991358}, 
 
\t {type: "School", name: "School 3", lat: 40.732056, lng: -73.998683} 
 
    ]; 
 

 
    //initialize map on document ready 
 
    $(document).ready(function(){ 
 
     var latlng = new google.maps.LatLng(40.723080, -73.984340); //you can use any location as center on map startup 
 
     var myOptions = { 
 
     zoom: 14, 
 
     center: latlng, 
 
     mapTypeControl: true, 
 
     mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}, 
 
     navigationControl: true, 
 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
 
     }; 
 
     map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
 
\t 
 
\t google.maps.event.addListener(map, 'click', showCloseLocations); 
 
    }); 
 
    
 
    function showCloseLocations(e) { 
 
    \t var i; 
 
    \t var radius_km = $('#radius_km').val(); 
 
    \t var address = $('#address').val(); 
 

 
    \t //remove all radii and markers from map before displaying new ones 
 
    \t if (radius_circle) { 
 
    \t \t radius_circle.setMap(null); 
 
    \t \t radius_circle = null; 
 
    \t } 
 
    \t for (i = 0; i < markers_on_map.length; i++) { 
 
    \t \t if (markers_on_map[i]) { 
 
    \t \t \t markers_on_map[i].setMap(null); 
 
    \t \t \t markers_on_map[i] = null; 
 
    \t \t } 
 
    \t } 
 
\t 
 
    \t var address_lat_lng = e.latLng; 
 
    \t radius_circle = new google.maps.Circle({ 
 
    \t \t center: address_lat_lng, 
 
    \t \t radius: radius_km * 1000, 
 
    \t \t clickable: false, 
 
    \t \t map: map 
 
    \t }); 
 
\t if(radius_circle) map.fitBounds(radius_circle.getBounds()); 
 
    \t for (var j = 0; j < all_locations.length; j++) { 
 
    \t \t (function (location) { 
 
    \t \t \t var marker_lat_lng = new google.maps.LatLng(location.lat, location.lng); 
 
    \t \t \t var distance_from_location = google.maps.geometry.spherical.computeDistanceBetween(address_lat_lng, marker_lat_lng); //distance in meters between your location and the marker 
 
    \t \t \t if (distance_from_location <= radius_km * 1000) { 
 
    \t \t \t \t var new_marker = new google.maps.Marker({ 
 
    \t \t \t \t \t position: marker_lat_lng, 
 
    \t \t \t \t \t map: map, 
 
    \t \t \t \t \t title: location.name 
 
    \t \t \t \t }); 
 
    \t \t \t \t google.maps.event.addListener(new_marker, 'click', function() { 
 
    \t \t \t \t \t alert(location.name + " is " + distance_from_location + " meters from my location"); 
 
    \t \t \t \t }); 
 
    \t \t \t \t markers_on_map.push(new_marker); 
 
    \t \t \t } 
 
    \t \t })(all_locations[j]); 
 
    \t } 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<script type="text/javascript" src="http://www.google.com/jsapi"></script> 
 
     <script type="text/javascript"> 
 
     google.load("maps", "3",{other_params:"sensor=false&libraries=geometry"}); 
 
     </script> 
 

 
<body style="margin:0px; padding:0px;" > 
 
    
 
<select id="radius_km"> 
 
\t <option value=1>1km</option> 
 
\t <option value=2>2km</option> 
 
\t <option value=5>5km</option> 
 
\t <option value=30>30km</option> 
 
</select> 
 
<div id="map_canvas" style="width:500px; height:300px;"> 
 
</body>

+0

Hola, el fragmento de código ya no funciona – aaa

+0

@ChingChongPa me funciona en Firefox. Depende de la configuración del navegador, etc., ya que carga el script http desde la página https. Pruébalo en tu servidor local, debería funcionar en cualquier navegador. Si obtiene el error "sin clave API", puede intentar cargar la API de Google Maps api como se describe aquí: https://developers.google.com/maps/documentation/javascript/tutorial en lugar de 'google.load (" mapas ".." del ejemplo. –

Cuestiones relacionadas