在不使用 Google Maps 的情况下将 Google Street View 集成到你的 React 应用中
Source: Dev.to
Introduction
Google Maps 提供了许多功能,但在高并发时的费用可能是个问题。你仍然可以在不显示完整 Google Map 的情况下将 Google Street View 集成到你的应用中。本指南展示了如何在 React 应用中使用 Leaflet 地图(该方法同样适用于任何地图提供商)嵌入 Street View,并概述了相关的限制。
Prerequisites
- Google Maps API Key – 按官方文档获取密钥并在 Google Cloud 项目中启用计费。
- Leaflet – 使用标准的 Leaflet 设置(无需 API 密钥)。
- React – 示例使用
react-leaflet以便更容易集成。
Adding the Google Maps script
在你的 index.html(或等价的入口文件)中添加脚本标签:
<!-- Insert your Google Maps script tag with your API key here -->
Pricing Overview
- Google Maps Platform 采用按使用量付费模式;每次加载 Street View 全景都会计费。
- 必须在提供 API 密钥的项目上启用计费。
- 相关 SKU 为 Dynamic Street View(参见 Google Maps 定价页面)。
- 截至 2026 年 2 月,每月前 10,000 次 Street View 调用免费。
Implementation
Install dependencies
npm install react-leaflet leaflet
# or with yarn
yarn add react-leaflet leaflet
Full App.tsx
import { MapContainer, TileLayer, Marker } from "react-leaflet";
import "./styles.css";
import { useEffect, useRef } from "react";
export default function App() {
const streetViewRef = useRef(null);
const location = [53.3957542, -1.3052656]; // latitude, longitude
useEffect(() => {
if (!window?.google || !streetViewRef.current) return;
new window.google.maps.StreetViewPanorama(streetViewRef.current, {
position: { lat: location[0], lng: location[1] },
pov: {
heading: 180,
pitch: 0,
},
zoom: 1,
});
}, [location]);
return (
{/* Street View container */}
);
}
Step‑by‑step explanation
- Create a
useRef(streetViewRef) that will hold the DOM element where Street View renders. - Load the Street View panorama inside a
useEffecthook once the Google Maps script (window.google) and the ref are available. - Pass the location (
lat&lng) tonew window.google.maps.StreetViewPanorama. Accurate coordinates are essential; an incorrect decimal place results in a blank view. - Render a container (“) with explicit width and height so the panorama is visible.
- The rest of the component sets up a basic Leaflet map with a marker at the same location.
Testing the coordinates
To find reliable latitude and longitude values:
- Open Google Maps, locate the desired Street View point.
- Inspect the network requests or use the “Share” → “Copy link” option and extract the
!3d(latitude) and!4d(longitude) parameters.
Running the example
- Insert your API key into the script tag in
index.html. - Start the React development server (
npm startoryarn start). - The map appears with a marker, and the Street View panorama loads below it.
If the panorama does not appear, verify that the container has non‑zero width/height and that the coordinates are correct.
Further resources
Feel free to explore the live CodeSandbox (add your API key) and adapt the implementation to your own project. Happy coding!