You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Maps API FindPlace请求异常,无法正确显示目标药店位置

核心问题
  • 你混淆了Google Maps两个不同的服务:你当前动态加载的script的地址是Places API HTTP查询接口,返回的是纯JSON,不能作为JS SDK加载,也无法直接获取到返回的JSON数据,你在网络请求里看到的返回正确,只是接口本身响应正常,但你的代码根本没拿到这个返回结果使用
  • 现有地图初始化逻辑完全只使用了当前定位的经纬度,没有读取药店的坐标信息,所以只会展示你的位置
解决方案

调整为正确的调用逻辑:先加载Google Maps JavaScript SDK(携带places库),再调用SDK内置的Find Place服务查询药店信息,最后用返回的药店坐标初始化地图/添加标记,修改后可用的代码如下:

<div id="map" style="height: 500px; width: 100%;"></div>
<script>
let map;
// 从ERB变量提前取出药店名称
const pharmacyName = "<%= @medicament['farmacies'].first['name'] %>";
const GOOGLE_MAP_KEY = "你的API密钥";

document.addEventListener("DOMContentLoaded", () => {
  // 第一步:加载Google Maps JavaScript SDK
  const mapScript = document.createElement("script");
  mapScript.src = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAP_KEY}&libraries=places&callback=initMap`;
  mapScript.async = true;
  mapScript.defer = true;
  document.head.appendChild(mapScript);
});

// SDK加载完成后自动执行的初始化回调
function initMap() {
  // 第二步:调用Find Place服务查询药店信息
  const request = {
    query: pharmacyName,
    fields: ['name', 'geometry', 'formatted_address'],
  };

  const service = new google.maps.places.PlacesService(document.createElement('div'));
  service.findPlaceFromQuery(request, (results, status) => {
    if (status === google.maps.places.PlacesServiceStatus.OK && results.length) {
      // 第三步:拿到药店坐标,初始化地图
      const pharmacyLocation = results[0].geometry.location;
      map = new google.maps.Map(document.getElementById("map"), {
        center: pharmacyLocation,
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });
      // 第四步:添加药店标记
      new google.maps.Marker({
        map: map,
        position: pharmacyLocation,
        title: results[0].name
      });

      // 如果需要同时展示当前定位,取消注释以下代码即可
      /*
      navigator.geolocation.getCurrentPosition((position) => {
        const myCoords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
        new google.maps.Marker({
          map: map,
          position: myCoords,
          title: "你的位置",
          icon: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"
        });
      }, () => {});
      */
    }
  });
}
</script>

注意事项

  • 前端直接暴露API密钥有被盗刷的风险,生产环境建议将Places查询逻辑放到后端实现,前端仅获取返回的坐标即可
  • 确保你的Google Cloud账号已经开启了Maps JavaScript API、Places API两个服务的访问权限,否则接口会报错

内容的提问来源于stack exchange,提问作者Milea David

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 13:45:03