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

如何在React中基于google-map-react实现自定义地图标记

使用google-map-react添加自定义标记

实现步骤:

  1. 创建自定义标记组件
    先写个自定义标记组件,样式可以按需调整,比如用文字提示、图标或者自定义形状:
const Marker = ({ text }) => (
  <div style={{
    backgroundColor: '#ff4444',
    color: 'white',
    padding: '8px 12px',
    borderRadius: '4px',
    fontSize: '14px',
    fontWeight: 'bold',
    boxShadow: '0 2px 4px rgba(0,0,0,0.2)'
  }}>
    {text}
  </div>
);
  1. 定义标记坐标数据
    在Map组件里,把需要添加的标记坐标整理成数组,每个元素包含纬度(lat)、经度(lng),还可以加自定义信息:
const markers = [
  { lat: 10.99835602, lng: 77.01502627, text: '默认中心点' },
  { lat: 11.0123, lng: 77.0345, text: '标记点1' },
  { lat: 10.9876, lng: 77.0012, text: '标记点2' }
];
  1. 在地图中渲染标记
    把自定义Marker组件作为GoogleMapReact的子元素,遍历标记数组,给每个Marker传入对应的坐标和自定义属性即可。

完整代码示例

import GoogleMapReact from "google-map-react";

// 自定义标记组件
const Marker = ({ text }) => (
  <div style={{
    backgroundColor: '#ff4444',
    color: 'white',
    padding: '8px 12px',
    borderRadius: '4px',
    fontSize: '14px',
    fontWeight: 'bold',
    boxShadow: '0 2px 4px rgba(0,0,0,0.2)'
  }}>
    {text}
  </div>
);

const Map = () => {
  const defaultProps = {
    center: {
      lat: 10.99835602,
      lng: 77.01502627,
    },
    zoom: 11,
  };

  // 标记坐标数据
  const markers = [
    { lat: 10.99835602, lng: 77.01502627, text: '默认中心点' },
    { lat: 11.0123, lng: 77.0345, text: '标记点1' },
    { lat: 10.9876, lng: 77.0012, text: '标记点2' }
  ];

  return (
    <div>
      <div style={{ height: "100vh", width: "100%" }}>
        <GoogleMapReact
          bootstrapURLKeys={{ key: "你的Google地图API密钥" }} // 替换为自己的API密钥
          defaultCenter={defaultProps.center}
          defaultZoom={defaultProps.zoom}
        >
          {/* 遍历渲染所有标记 */}
          {markers.map((marker, index) => (
            <Marker
              key={index}
              lat={marker.lat}
              lng={marker.lng}
              text={marker.text}
            />
          ))}
        </GoogleMapReact>
      </div>
    </div>
  );
};

export default Map;

关键说明

  • GoogleMapReact的子组件必须传入lat和lng属性,组件会自动将标记定位到对应坐标位置。
  • 自定义Marker组件的样式完全可定制,比如换成图片图标:把div内容替换为<img src="你的图标路径" alt="标记" style={{width: '30px', height: '30px'}} />即可。
  • 务必替换代码中的你的Google地图API密钥,否则地图无法正常加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 14:54:19