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

如何在React Google Map中显示当前位置图标?

在React Google Map中显示当前位置图标

嘿,我来帮你搞定这个问题!虽然官方文档里没有直接提供显示当前位置的专属props,但我们可以通过浏览器原生Geolocation API结合react-google-maps的Marker组件来实现这个功能,具体步骤和修改后的代码如下:

实现思路

  1. 获取用户当前位置:利用浏览器的navigator.geolocation API获取用户的经纬度信息,存入组件状态中
  2. 渲染当前位置标记:在GoogleMap组件内新增一个Marker,用获取到的位置作为坐标,还可以自定义图标样式模拟原生定位圆点效果

修改后的完整组件代码

const googleMapCard = compose(
  withProps({
    googleMapURL: "https://maps.googleapis.com/maps/api/js?key=-----------",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />
  }),
  lifecycle({
    componentDidMount() {
      const refs = {};
      
      // 调用Geolocation API获取当前位置
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            this.setState({
              currentLocation: {
                lat: position.coords.latitude,
                lng: position.coords.longitude
              }
            });
          },
          (error) => {
            console.error("获取当前位置失败:", error);
          }
        );
      }

      this.setState({
        bounds: null,
        markers: [],
        onMapMounted: ref => {
          refs.map = ref;
        },
        onBoundsChanged: () => {
          this.setState({
            bounds: refs.map.getBounds(),
            center: refs.map.getCenter()
          });
        },
        onSearchBoxMounted: ref => {
          refs.searchBox = ref;
        },
        onPlacesChanged: onChange => {
          const places = refs.searchBox.getPlaces();
          const bounds = new window.google.maps.LatLngBounds();
        }
      });
    }
  }),
  withScriptjs,
  withGoogleMap
)(props => (
  <GoogleMap
    onClick={e => {
      props.onChange([e.latLng.lng(), e.latLng.lat()]);
    }}
    clickableIcons={true}
    defaultZoom={8}
    center={{ lat: props.value[1], lng: props.value[0] }}
    defaultCenter={{ lat: props.value[1], lng: props.value[0] }}
    ref={props.onMapMounted}
  >
    <SearchBox
      ref={props.onSearchBoxMounted}
      controlPosition={window.google.maps.ControlPosition.TOP_LEFT}
      onPlacesChanged={() => {
        props.onPlacesChanged(props.onChange);
      }}
    >
      <input type="text" />
    </SearchBox>
    {/* 原有位置标记 */}
    <Marker position={{ lat: props.value[1], lng: props.value[0] }} />
    {/* 当前位置标记 */}
    {props.currentLocation && (
      <Marker
        position={props.currentLocation}
        icon={{
          url: "https://maps.gstatic.com/mapfiles/ms/micons/blue-dot.png", // 自定义定位图标
          scaledSize: new window.google.maps.Size(30, 30)
        }}
        title="你的当前位置"
      />
    )}
  </GoogleMap>
));

额外注意点

  • 权限提示:浏览器会自动向用户请求位置访问权限,用户允许后才能获取到位置信息
  • 图标自定义:你可以替换icon.url为自己的图标地址,或者调整scaledSize来修改图标大小
  • 错误处理:代码中添加了获取位置失败的日志,你可以根据需求改成用户可见的提示UI

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:32:30