如何通过JavaScript调用Google Map API获取周边全部咖啡馆?
利用JavaScript调用Google Maps API获取周边咖啡馆的实现方案
1. 准备API密钥
- 先在Google Cloud控制台创建项目,启用Places API和Geolocation API
- 生成专属API密钥,建议给密钥设置域名绑定等访问限制,防止滥用
2. 加载Maps JavaScript API
在HTML中引入包含Places库的API脚本,替换成你的密钥:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=你的API密钥&libraries=places&callback=initMap"></script>
3. 获取当前地理位置
用浏览器原生API获取用户当前坐标:
function getCurrentLocation() { return new Promise((resolve, reject) => { if (!navigator.geolocation) { reject("浏览器不支持地理定位功能"); return; } navigator.geolocation.getCurrentPosition( (position) => { resolve({ lat: position.coords.latitude, lng: position.coords.longitude }); }, (error) => { reject(`定位失败:${error.message}`); } ); }); }
4. 搜索周边咖啡馆
借助Google Maps的PlacesService执行附近搜索:
async function initMap() { try { const userLocation = await getCurrentLocation(); // 可选:创建地图实例用于可视化展示 const map = new google.maps.Map(document.getElementById("map"), { center: userLocation, zoom: 15 }); // 初始化Places服务 const placesService = new google.maps.places.PlacesService(map); // 搜索参数配置 const searchRequest = { location: userLocation, radius: 1000, // 搜索半径,单位:米 type: ["cafe"] // 指定搜索类型为咖啡馆 }; // 执行搜索并处理结果 placesService.nearbySearch(searchRequest, (results, status) => { if (status === google.maps.places.PlacesServiceStatus.OK) { results.forEach(place => { console.log(`名称:${place.name},地址:${place.vicinity}`); // 可选:在地图上标记咖啡馆位置 new google.maps.Marker({ position: place.geometry.location, map: map, title: place.name }); }); } else { console.error(`搜索失败:${status}`); } }); } catch (err) { console.error(err); } }
关键注意事项
- 必须在HTTPS环境下运行(本地localhost除外),否则地理定位API无法正常工作
- 注意Google API的配额限制,超出配额会导致请求失败
- 确保API密钥已启用所需的Places和Geolocation API,否则会返回权限错误
内容的提问来源于stack exchange,提问作者simo
相关产品推荐
相关产品推荐

