让我们尝试为您提供一些第一步,我不会编写整个应用程序的代码,而是为您提供一些如何解决您遇到的小子问题的指导方针:
在地图中添加圆圈
好吧,为此你有很多不同的输入选项,但最重要的部分是 addCircle 函数:
function addCircle(center){
circle = new google.maps.Circle({
map: map, //The existing map
center: center,
radius: 200, //This will be modified afterwards
zindex: 100
});
}
该中心可能来自click https://developers.google.com/maps/documentation/javascript/examples/event-simple例如:
// Area is wherever you want to attach the click, either a polygon, a map...
google.maps.event.addListener(area, "click", function(event) {
addCircle(event.latLng);
});
或者通过获取某个地址的位置(这也有记录 https://developers.google.com/maps/documentation/geocoding/start?csw=1),或任何方法(拖放圆圈,拖动标记 blablabla)
添加动态半径
好吧,如果我们知道的话圆的半径以米为单位 https://developers.google.com/maps/documentation/javascript/shapes#circles,然后很容易为 addCircle 函数提供正确的半径。例如,20公里->20000米。所以你只需要在调用 addCircle 时能够访问 radius (它可以是一个参数,一个全局变量......你的选择)。
我们已经完成了绘图部分,现在让我们在该圆圈内进行搜索。
仅获取圆圈内的标记
这里有一个先决条件,那就是拥有地图上的所有标记。您可能有一系列从数据库中获取的位置,或者也许您从 Google Maps API 获取标记 https://developers.google.com/maps/documentation/javascript/examples/place-search(例如地点搜索)。
之后,您将必须计算这些标记与给定中心之间的距离,并检查该距离是否小于您的半径(使用计算之间的距离 https://developers.google.com/maps/documentation/javascript/reference/3/#spherical非常简单),这样您就会知道哪些标记对您有效。
const markers = [//array of my valid markers with position];
markers.filter( (marker) =>
google.maps.geometry.spherical.computeDistanceBetween(marker.getPosition(), center.getPosition()) < radius; // Filter the markers which distance is bigger than radius;
剩下的工作应该很简单将标记放置在地图中 https://developers.google.com/maps/documentation/javascript/examples/marker-simple并利用这些信息做任何你想做的事。
EXTRAS
作为进一步的帮助,有一对可能对您有用的示例/答案:
完整的 Google 地图 API 示例 https://mono.software/2017/02/22/google-maps-javascript-api-intro/,非常简单的分步指南。
使用地点进行半径搜索 https://stackoverflow.com/questions/18364715/google-maps-api-radius-search-for-markers-using-places,关于如何进行半径搜索的一个很好的答案。
半径搜索示例 http://www.geocodezip.com/v3_MW_example_map3_radiusSearch.html,如果愿意的话,打开 F12 并调试代码,但很容易理解。
编辑**:我没有意识到其中的两个链接也在评论中指出。