I'm using the Google Maps JavaScript API and this solution for getting closest points on the map and displaying them.
function findClosestN(pt,numberOfResults) {
var closest = [];
for (var i=0; i<gmarkers.length;i++) {
gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt,gmarkers[i].getPosition());
gmarkers[i].setMap(null);
closest.push(gmarkers[i]);
}
closest.sort(sortByDist);
return closest;
}
function sortByDist(a,b) {
return (a.distance- b.distance)
}
function calculateDistances(pt,closest,numberOfResults) {
var service = new google.maps.DistanceMatrixService();
var request = {
origins: [pt],
destinations: [],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
};
for (var i=0; i<closest.length; i++) request.destinations.push(closest[i].getPosition());
service.getDistanceMatrix(request, function (response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('search_results');
outputDiv.innerHTML = '';
photo_lat = closest[i].lat; // lat
photo_lng = closest[i].lng; // lng
profile_photo = "https://maps.googleapis.com/maps/api/streetview?size=600x300&location=" + photo_lat + "," + photo_lng + "&heading=151.78&pitch=-0.76";
var results = response.rows[0].elements;
for (var i = 0; i < numberOfResults; i++) {
closest[i].setMap(map);
outputDiv.innerHTML += "<div class='location_list' style='background:url(" + profile_photo + ");'>" + "<div class='inner'>" + "<a href='javascript:google.maps.event.trigger(closest["+i+"],\"click\");'>"+closest[i].title + '</a><br>' + closest[i].address+"<br>"
+ results[i].distance.text + ' appoximately '
+ results[i].duration.text
+ "</div></div>";
}
}
});
}
In the calculateDistances method, I'd now like to get the lat and lng values for each of the "closest" results. Then I would like to pass each of these lat/lng pairs into the Street View Image API to display a static street view image of each location:
photo_lat = closest[i].lat; // lat
photo_lng = closest[i].lng; // lng
closest[i] doesn't seem to be the correct target though. How can I extract the lat/lng from each "closest" result within the method?
<style> html { height: 100%; } body { height: 100%; margin: 0; padding: 0; font-size: 26px; font-family: "filson-soft"; } #map_container { height: 700px; } #map { width: 80%; height: 100%; float: left; } #locations_list { width: 20%; height: 100%; overflow-y: scroll; float: left; } .location_list { color: #ffffff; height: 140px; background-size: 100% !important; background-position: center !important; } #search_results { font-size: 14px; } #search_results .inner { padding-left: 10px; padding-right: 10px; padding-top: 60px; } </style> <div id="map_container"> <div id="map"></div> <div id="locations_list"> <div id="search_results"></div> </div> </div> <script> google.maps.event.addDomListener(window, "load", initMap); var geocoder; var map; var locations; var gmarkers = []; var closest = []; var search_lat; var search_lng; var infowindow; var directionsDisplay; var directionsService; function initMap() { gmarkers = []; directionsDisplay = new google.maps.DirectionsRenderer(); directionsService = new google.maps.DirectionsService; geocoder = new google.maps.Geocoder(); // SET THE CENTER OF THE MAP var theCenter = { lat: 38.5803844, lng: -121.50024189999999 }; // ADD THE MAP AND SET THE MAP OPTIONS map = new google.maps.Map(document.getElementById('map'), { zoom: 16, center: theCenter }); locations = [ ["Joes Parking Garage","1001 6th St","Sacramento","CA","95814","38.58205649","-121.49857521","parking_garage"], ["Mikes Parking Garage","918 5th St","Sacramento","CA","95814","38.5826939","-121.50012016","parking_garage"] ]; infowindow = new google.maps.InfoWindow(); var marker, i; var bounds = new google.maps.LatLngBounds(); console.log("found " + locations.length + " locations<br>"); for (i = 0; i < locations.length; i++) { var icon_image = 'http://maps.google.com/mapfiles/ms/micons/parkinglot.png'; var coordStr = locations[i][5] + "," + locations[i][6]; var coords = coordStr.split(","); var pt = new google.maps.LatLng(parseFloat(coords[0]),parseFloat(coords[1])); bounds.extend(pt); var location_name = locations[i][0]; var location_address = locations[i][1] + ', ' + locations[i][2] + ', ' + locations[i][3] + ' ' + locations[i][4]; marker = new google.maps.Marker({ position: pt, animation: google.maps.Animation.DROP, icon: icon_image, map: map, title: location_name, address: location_address }); gmarkers.push(marker); } var address = "547 L St, Sacramento, CA 95814"; geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { search_lat = results[0].geometry.location.lat(); search_lng = results[0].geometry.location.lng(); console.log('search address coordinates: ' + search_lat + ', ' + search_lng); closest = findClosestN(results[0].geometry.location,10); // get driving distance closest = closest.splice(0,10); calculateDistances(results[0].geometry.location, closest,10); //calculateAndDisplayRoute(directionsService, directionsDisplay); } else { alert("Geocode was not successful for the following reason: " + status); } }); } function findClosestN(pt,numberOfResults) { var closest = []; //document.getElementById('info').innerHTML += "processing "+gmarkers.length+"<br>"; for (var i=0; i<gmarkers.length;i++) { gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt,gmarkers[i].getPosition()); // document.getElementById('info').innerHTML += "process "+i+":"+gmarkers[i].getPosition().toUrlValue(6)+":"+gmarkers[i].distance.toFixed(2)+"<br>"; gmarkers[i].setMap(null); closest.push(gmarkers[i]); } closest.sort(sortByDist); return closest; } function sortByDist(a,b) { return (a.distance- b.distance); } function calculateDistances(pt,closest,numberOfResults) { var service = new google.maps.DistanceMatrixService(); var request = { origins: [pt], destinations: [], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.IMPERIAL, avoidHighways: false, avoidTolls: false }; for (var i=0; i<closest.length; i++) request.destinations.push(closest[i].getPosition()); service.getDistanceMatrix(request, function (response, status) { if (status != google.maps.DistanceMatrixStatus.OK) { alert('Error was: ' + status); } else { var origins = response.originAddresses; var destinations = response.destinationAddresses; var outputDiv = document.getElementById('search_results'); outputDiv.innerHTML = ''; var results = response.rows[0].elements; for (var i = 0; i < numberOfResults; i++) { closest[i].setMap(map); photo_lat = closest[i].getPosition().lat(); // lat photo_lng = closest[i].getPosition().lng(); // lng profile_photo = "https://maps.googleapis.com/maps/api/streetview?sensor=false&size=600x300&location=" + photo_lat + "," + photo_lng + "&heading=151.78&pitch=-0.76"; outputDiv.innerHTML += "<div class='location_list' style='background:url(" + profile_photo + ");'>" + "<div class='inner'>" + "<a href='javascript:google.maps.event.trigger(closest["+i+"],\\"click\\");'>"+closest[i].title + '</a><br>' + closest[i].address+"<br>" + results[i].distance.text + ' appoximately ' + results[i].duration.text + "</div></div>"; } } }); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&callback=initMap"></script> </body> </html>
The elements of the closest
array are google.maps.Marker objects. To get their location, call their .getPosition()
method (returns a google.maps.LatLng
object).
photo_lat = closest[i].getPosition().lat(); // lat
photo_lng = closest[i].getPosition().lng(); // lng
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.