2012-05-23 23 views
8

¿Alguien sabe cómo utilizar el rango por la opción de búsqueda de distancia que se menciona aquí? https://developers.google.com/maps/documentation/javascript/places#place_search_requestsgoogle maps api v3 cómo clasificar por distancia más cercana

Al mencionar esto en las opciones de solicitud no parece funcionar. Aquí está mi porción de código en relación con esto:

var request = { 
    location: coords, 
    //radius: 30000, 
    keyword: ['puma, retail'], 
    types: ['store'], 
    rankBy: google.maps.places.RankBy.DISTANCE 
}; 

service = new google.maps.places.PlacesService(map); 
service.search(request, callback); 

function callback(results, status) { 
    if (status == google.maps.places.PlacesServiceStatus.OK) { 
     for (var i = 0; i < results.length; i++) { 
      createMarker(results[i]); 
          listResults(results[i]); 
     } 
    } 
} 

Código localizará y la lista de resultados si incluyo un radio, pero los resultados no se enumeran en orden ascendente por la distancia. Los documentos de Google dicen que tampoco es necesario un radio si se usa la opción rankBy. ¿Me estoy perdiendo de algo?

+0

Estoy en el mismo barco ... buscando una solución. – GuiDoody

Respuesta

7

Estaba teniendo el mismo problema. Según esta fuente: http://www.geocodezip.com/v3_GoogleEx_place-search.html I fue capaz de formular la consulta como tal:

var request = { 
location: gps, 
types: ['food'], //You can substitute "keyword: 'food'," (without double-quotes) here as well. 
rankBy: google.maps.places.RankBy.DISTANCE, //Note there is no quotes here, I made that mistake. 
key: key 
}; 

clave Var es la clave API que no se requiere, pero añadió para su uso posterior. GPS es:

var gps = new google.maps.LatLng(location.lat,location.lon); 

Por último, hice todo lo que hicieron, excepto añadí límites de un mapa que no iba a utilizar. Para eso lo hice:

var bounds = new google.maps.LatLngBounds(); 
3

No se pueden usar radius + rankBy propiedades juntas.

Si necesita las ubicaciones más cercanas, elija algunos tipos y establezca el rango Por propiedad.

places.nearbySearch({ 
         location: LatLng, 
         types: placeTypes, 
         rankBy: google.maps.places.RankBy.DISTANCE 
        }, 
        function (results) { 
         // process the results, r[0] is the closest place 
        } 
       ); 

donde se puede establecer cirugíaTipos como esto

var placeTypes = [ 
'accounting', 
'airport', 
'amusement_park', 
'aquarium', 
'art_gallery', 
'atm', 
'bakery', 
'bank', 
'bar', 
'beauty_salon', 
'bicycle_store', 
'book_store', 
'bowling_alley', 
'bus_station', 
'cafe', 
'campground', 
'car_dealer', 
'car_rental', 
'car_repair', 
'car_wash', 
'casino', 
'cemetery', 
'church', 
'city_hall', 
'clothing_store', 
'convenience_store', 
'courthouse', 
'dentist', 
'department_store', 
'doctor', 
'electrician', 
'electronics_store', 
'embassy', 
'establishment', 
'finance', 
'fire_station', 
'florist', 
'food', 
'funeral_home', 
'furniture_store', 
'gas_station', 
'general_contractor', 
'grocery_or_supermarket', 
'gym', 
'hair_care', 
'hardware_store', 
'health', 
'hindu_temple', 
'home_goods_store', 
'hospital', 
'insurance_agency', 
'jewelry_store', 
'laundry', 
'lawyer', 
'library', 
'liquor_store', 
'local_government_office', 
'locksmith', 
'lodging', 
'meal_delivery', 
'meal_takeaway', 
'mosque', 
'movie_rental', 
'movie_theater', 
'moving_company', 
'museum', 
'night_club', 
'painter', 
'park', 
'parking', 
'pet_store', 
'pharmacy', 
'physiotherapist', 
'place_of_worship', 
'plumber', 
'police', 
'post_office', 
'real_estate_agency', 
'restaurant', 
'roofing_contractor', 
'rv_park', 
'school', 
'shoe_store', 
'shopping_mall', 
'spa', 
'stadium', 
'storage', 
'store', 
'subway_station', 
'synagogue', 
'taxi_stand', 
'train_station', 
'travel_agency', 
'university', 
'veterinary_care', 
'zoo' 

];

13

No puede usar las propiedades de radio y RankBy.DISTANCE juntas. Por lo tanto, tiene dos opciones:

1) Busque por radio y luego clasifique los resultados por distancia en su propio código.

Ejemplo:

var request = { 
       location: coords, 
       radius: 30000, 
       keyword: ['puma, retail'], 
       types: ['store'] 
       }; 
service = new google.maps.places.PlacesService(map); 
service.search(request, callback); 

function callback(results, status) { 
     if (status == google.maps.places.PlacesServiceStatus.OK) { 
      for (var i = 0; i < results.length; i++) { 
      sortresults(results[i]);//sortresult uses haversine to calcuate distance and then arranges the result in the order of distance 
      createMarker(results[i]); 
      listResults(results[i]); 
     } 
    } 
} 

Opción 2: Búsqueda por RankBy.Distance luego tapar el resultado utilizando el radio. De nuevo necesitaría la fórmula de haversine para calcular distancias.

var request = { 
       location: coords, 
       rankBy: google.maps.places.RankBy.DISTANCE, 
       keyword: ['puma, retail'], 
       types: ['store'] 
       }; 
service = new google.maps.places.PlacesService(map); 
service.search(request, callback); 

function callback(results, status) { 
     if (status == google.maps.places.PlacesServiceStatus.OK) { 

      for (var i = 0; i < results.length; i++) { 
      d= distance(coords,results[i].latlng) 
      if(d<rd) 
      {createMarker(results[i]); 
      listResults(results[i]); 
      } 
      } 
    } 
} 

//Returns Distance between two latlng objects using haversine formula 
distance(p1, p2) { 
if (!p1 || !p2) 
    return 0; 
var R = 6371000; // Radius of the Earth in m 
var dLat = (p2.lat() - p1.lat()) * Math.PI/180; 
var dLon = (p2.lng() - p1.lng()) * Math.PI/180; 
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
Math.cos(p1.lat() * Math.PI/180) * Math.cos(p2.lat() * Math.PI/180) * 
Math.sin(dLon/2) * Math.sin(dLon/2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); 
var d = R * c; 
return d; 
} 
+0

Esta fue definitivamente la respuesta correcta para mí, tuve el mismo problema que @JFlo – David

1

Tenga en cuenta que en la actual Api Doc el método de "búsqueda" en la clase PlacesService no está disponible.

https://developers.google.com/maps/documentation/javascript/reference?hl=it#PlacesService

Tienes que elegir Transcurrirá:

  • nearbySearch (recuperar 20 Resultados por página, máximo 3 páginas)
  • radarSearch (recuperar 200 resultado pero con menos detalles)
  • TEXTSEARCH (similar a la Búsqueda cercana)

Si decide RankBy.DISTANCE usted no puede configurar el radio

var request = { 
    location: vLatLng, 
    //radius: vRaggio, 
    rankBy: google.maps.places.RankBy.DISTANCE, 
    keyword: ['puma, retail'], 
    types: ['store'] 
} 

placesService.nearbySearch(request, function (data, status, placeSearchPagination) { 
    if (status == google.maps.places.PlacesServiceStatus.OK) { 
    //... 
    // do your stuffs with data results 
    //... 
    if (placeSearchPagination && placeSearchPagination.hasNextPage) { 
    placeSearchPagination.nextPage(); 
    } 
}); 

Si desea restringir los datos basados ​​en un radio de distancia se puede utilizar esta función para comprobar si el resut está demasiado lejos.

function checkRadiusDistance(place,centerLatLng,radius) { 
    return google.maps.geometry.spherical.computeDistanceBetween(place.geometry.location, centerLatLng) < radius; 
}); 

Tenga en cuenta que esta es también la única manera de obtener lugares dentro de un radio determinado por culpa cuando se especifica "rankBy: google.maps.places.RankBy.PROMINENCE" y un "radio = xx "the placesService give you también resulta fuera del área definida.

Cuestiones relacionadas