You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

React Js集成Google Map技术求助:需获取指定POI,寻求免费API库替代google-map-react

替代google-map-react的React Google Maps免费集成方案(针对POI需求)

嘿,我懂你在React项目里用google-map-react实现指定POI(酒店、ATM、银行、医院)的Google Maps集成时遇到了麻烦,这里给你几个靠谱的免费替代方案,都是适配React的,能很好满足你的POI获取需求:


1. @react-google-maps/api(官方推荐的React封装)

这是Google官方维护的React组件库,完全免费(只要你符合Google Maps API的免费额度政策),功能完整,对POI搜索和展示的支持非常到位。

实现步骤:

首先安装依赖:

npm install @react-google-maps/api
# 或者用yarn
yarn add @react-google-maps/api

然后编写核心组件示例,实现指定POI的搜索与展示:

import React, { useState, useEffect } from 'react';
import { GoogleMap, LoadScript, Marker } from '@react-google-maps/api';

// 地图容器样式
const mapContainerStyle = {
  width: '100%',
  height: '800px'
};

// 默认地图中心(示例为纽约坐标,可替换成你需要的位置)
const defaultCenter = {
  lat: 40.7128,
  lng: -74.0060
};

// 你需要的POI类型列表
const targetPOITypes = ['hotels', 'atms', 'banks', 'hospitals'];

const MapWithPOIs = () => {
  const [poiMarkers, setPoiMarkers] = useState([]);

  useEffect(() => {
    // 初始化Places服务(需要创建一个虚拟DOM元素承载服务)
    const placesService = new window.google.maps.places.PlacesService(document.createElement('div'));

    targetPOITypes.forEach(type => {
      const searchRequest = {
        location: defaultCenter,
        radius: '5000', // 搜索半径,单位为米
        type: type
      };

      // 发起附近POI搜索
      placesService.nearbySearch(searchRequest, (results, status) => {
        if (status === window.google.maps.places.PlacesServiceStatus.OK) {
          // 将搜索结果转换为标记数据
          const newMarkers = results.map(place => ({
            lat: place.geometry.location.lat(),
            lng: place.geometry.location.lng(),
            title: `${place.name} (${type})`,
            address: place.vicinity
          }));
          setPoiMarkers(prev => [...prev, ...newMarkers]);
        }
      });
    });
  }, []);

  return (
    <LoadScript
      googleMapsApiKey="YOUR_GOOGLE_MAPS_API_KEY" // 替换成你的API密钥
      libraries={['places']} // 必须加载places库才能使用POI搜索
    >
      <GoogleMap
        mapContainerStyle={mapContainerStyle}
        center={defaultCenter}
        zoom={12}
      >
        {/* 渲染所有POI标记 */}
        {poiMarkers.map((marker, index) => (
          <Marker
            key={index}
            position={{ lat: marker.lat, lng: marker.lng }}
            title={marker.title}
            onClick={() => alert(`地址:${marker.address}`)} // 可自定义点击事件
          />
        ))}
      </GoogleMap>
    </LoadScript>
  );
};

export default MapWithPOIs;

优势:

  • 官方维护,兼容性和稳定性拉满
  • 直接对接Google Places API,POI数据准确全面
  • 支持自定义标记样式、信息窗口、搜索范围等扩展功能

2. react-google-maps(社区维护的经典库)

这是个成熟的社区封装库,虽然不是官方出品,但功能完善、文档齐全,同样免费使用(依赖Google Maps API的免费额度)。

安装依赖:

npm install react-google-maps
# 或者用yarn
yarn add react-google-maps

简单实现示例:

import React, { useState, useEffect } from 'react';
import { withGoogleMap, GoogleMap, Marker, withScriptjs } from 'react-google-maps';

// 创建地图组件
const BaseMap = withScriptjs(withGoogleMap(({ markers }) => (
  <GoogleMap
    defaultZoom={12}
    defaultCenter={{ lat: 40.7128, lng: -74.0060 }}
  >
    {markers.map((marker, index) => (
      <Marker key={index} position={marker.position} title={marker.title} />
    ))}
  </GoogleMap>
)));

const POIMap = () => {
  const [poiMarkers, setPoiMarkers] = useState([]);

  useEffect(() => {
    const placesService = new window.google.maps.places.PlacesService(document.createElement('div'));
    const targetPOITypes = ['hotels', 'atms', 'banks', 'hospitals'];

    targetPOITypes.forEach(type => {
      placesService.nearbySearch({
        location: { lat: 40.7128, lng: -74.0060 },
        radius: 5000,
        type: type
      }, (results, status) => {
        if (status === window.google.maps.places.PlacesServiceStatus.OK) {
          const newMarkers = results.map(place => ({
            position: place.geometry.location,
            title: `${place.name} (${type})`
          }));
          setPoiMarkers(prev => [...prev, ...newMarkers]);
        }
      });
    });
  }, []);

  return (
    <BaseMap
      googleMapURL="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY&libraries=places"
      loadingElement={<div style={{ height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>加载中...</div>}
      containerElement={<div style={{ height: '800px' }} />}
      mapElement={<div style={{ height: '100%' }} />}
      markers={poiMarkers}
    />
  );
};

export default POIMap;

优势:

  • 社区活跃,有大量教程和问题解决方案可以参考
  • 支持Places API的多种搜索方式(附近搜索、文本搜索等)
  • 组件化程度高,容易和现有React项目无缝集成

关键注意事项

  • 不管用哪个库,都需要先申请Google Maps API密钥,并在控制台启用「Places API」和「Maps JavaScript API」
  • Google Maps API有免费额度,超出后会产生费用,建议在Google Cloud控制台监控使用情况
  • 你可以根据需求自定义POI的搜索半径、过滤条件(比如添加关键词、评级筛选等)

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

火山引擎 最新活动