如何使用Google Places Javascript API搜索附近的位置(自动从浏览器获取坐标)

How to search for nearby (getting coordinates from browser automatically) with Google Places Javascript API?

本文关键字:浏览器 坐标 获取 位置 Places Google 何使用 Javascript API 搜索      更新时间:2023-09-26

我正在开发一个网站,我需要一个文本框,里面预装了来自 Google 地方信息的最近城市。我目前正在使用自动完成功能搜索附近,这确实要求浏览器的位置权限,但是如何使用 API 本身搜索附近的城市,而无需费心从浏览器获取用户的位置并将其传递到 Google Places API 调用中?由于谷歌无论如何都已经从浏览器中获取了我的位置,它不应该(逻辑上)根据我在nearbySearch的当前位置搜索附近的地点,还是有其他方法?

好的,

我最终从浏览器本机获取位置,然后将位置传递给 Places API,因为 Places API 显然没有这种(非常基本的)功能。这是我获得位置的方式:

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
        var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
        //service is a PlacesService instance.
        var req = {
            location: pos,
            radius: '50000',
            types: ['(cities)']
        };
        service.nearbySearch(req, function (results, status) {
           ...
        });
}