Reputation: 9
I am building a function that will show only the closest park from user's current location. Right now my code is showing all the park nearby the user, given a radius.
But I am not being able to show that only one park that is located the closest to the user. My code right now looks like this. Can anybody help me by telling me how can I only show the closest park?
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 80%;
width: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?key=**MY_KEY**&libraries=places,geometry"
async defer></script>
</head>
<body>
<div id="map"></div>
<script type ="text/javascript">
var map;
var coords;
var infowindow;
var markerPos;
var markers;
var place;
var directionsDisplay;
var directionsService;
//Retrives the location from the browser
x = navigator.geolocation;
x.getCurrentPosition(success, failure);
function success(position){
directionsDisplay = new google.maps.DirectionsRenderer;
directionsService = new google.maps.DirectionsService;
//Get user's longitude and latitude
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
//Creating new object for using the latitude and longitude values with Google Maps
coords = new google.maps.LatLng(myLat,myLong);
//Map options
var mapOptions = {
zoom: 13,
center: coords
}
map = new google.maps.Map(document.getElementById("map"),mapOptions);
infowindow = new google.maps.InfoWindow();
directionsDisplay.setMap(map);
directionsDisplay.setOptions( { suppressMarkers: true, preserveViewport: true } );
addNearByPlaces(coords);
// create marker on my postion
var myPos =new google.maps.Marker({
map:map,
position:coords,
animation: google.maps.Animation.BOUNCE
});
}
function failure(){
alert("Geolocation is not supported by the browser.");
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, coords, markerPos) {
// var selectedMode = document.getElementById('mode').value;
directionsService.route({
origin: coords, // Haight.
destination: markerPos, // Ocean Beach.
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode.WALKING
}, function(response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
function addNearByPlaces(coords){
var service = new google.maps.places.PlacesService(map);
var request = {
location: coords,
//Defines the distance (in meters)
radius: 10936,
types: ['park']
};
service.nearbySearch(request, callback);
}
function callback(results, status) {
var markers = [];
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
markers.push(createMarker(results[i]));
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function(event) {
var latitude = this.position.lat();
var longitude = this.position.lng();
markerPos = {lat: latitude, lng: longitude};
calculateAndDisplayRoute(directionsService, directionsDisplay,coords, markerPos);
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
</script>
</body>
</body>
</html>
Upvotes: 0
Views: 530
Reputation: 376
Try changing your request to
var request = {
location: coords,
rankBy: google.maps.places.RankBy.DISTANCE,
types: ['park']
};
Then in the callback look at results[0]
for the nearest result.
Upvotes: 1