谷歌地图显示最近的带有标记的公园

时间:2018-05-23 13:48:28

标签: javascript html google-maps-api-3

我正在构建一个功能,只显示距离用户当前位置最近的公园。现在我的代码显示了半径范围内用户附近的所有公园。

但我无法证明只有一个公园位于距离用户最近的位置。我的代码现在看起来像这样。 任何人都可以通过告诉我如何才能显示最近的公园来帮助我?

<!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>

1 个答案:

答案 0 :(得分:1)

尝试将您的请求更改为

var request = {
    location: coords,
    rankBy: google.maps.places.RankBy.DISTANCE,
    types: ['park']
};

然后在回调中查看results[0]以获得最近的结果。