如何修改Google Maps代码仅显示用户当前位置最近的公园标记?
实现仅显示最近公园的解决方案
没问题,我帮你调整代码实现只显示距离用户当前位置最近的公园。核心思路是计算每个返回公园与用户位置的距离,筛选出距离最小的那个,再单独创建标记,具体修改如下:
关键修改步骤
- 利用Google Maps Geometry库的
computeDistanceBetween方法计算直线距离(你的API链接已经引入了geometry库,不用额外操作) - 在
callback函数中遍历所有公园结果,筛选出距离最近的那个 - 仅为最近的公园创建标记,不再渲染所有结果
修改后的完整代码
<!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) { if (status === google.maps.places.PlacesServiceStatus.OK) { let closestPark = null; let minDistance = Infinity; // 遍历所有公园,计算距离并筛选最近的 results.forEach(park => { const distance = google.maps.geometry.spherical.computeDistanceBetween( coords, park.geometry.location ); if (distance < minDistance) { minDistance = distance; closestPark = park; } }); // 为最近的公园创建标记 if (closestPark) { createMarker(closestPark); // 可选:自动打开信息窗口 // infowindow.setContent(closestPark.name); // infowindow.open(map, createMarker(closestPark)); } } else { alert('未找到附近的公园'); } } 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); }); return marker; } </script> </body> </html>
修改说明
- 核心修改在
callback函数:我们不再循环创建所有标记,而是先遍历所有公园结果,用computeDistanceBetween计算每个公园到用户位置的距离,记录下距离最小的公园 - 增加了异常处理:当没有找到公园时弹出提示
- 保留了原有的点击标记显示路线功能,仅针对最近的公园生效
如果需要调整半径或者修改距离计算方式(比如用驾车/步行距离而非直线距离),可以再进一步调整逻辑哦!
内容的提问来源于stack exchange,提问作者Little little
相关产品推荐
相关产品推荐

