我正在使用Google Maps JavaScript API和this solution来获取地图上最近的点并显示它们。
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>";
}
}
});
}
在calculateDistances方法中,我现在想要得到每个“最接近”结果的lat和lng值。然后我想将每个lat / lng对传递到街景图像API中,以显示每个位置的静态街景图像:
photo_lat = closest[i].lat; // lat
photo_lng = closest[i].lng; // lng
最近[i]似乎不是正确的目标。如何从方法中的每个“最接近”结果中提取lat / lng?
<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>
答案 0 :(得分:1)
closest
数组的元素是google.maps.Marker个对象。要获取其位置,请调用他们的.getPosition()
方法(返回google.maps.LatLng
对象)。
photo_lat = closest[i].getPosition().lat(); // lat
photo_lng = closest[i].getPosition().lng(); // lng