reactjs - 在 React 中向 Google 地图添加自定义样式
问题描述
我正在尝试在我的 React 应用程序中向 Google Map 添加自定义样式,我可以在其中显示地图,但是在为地图定义样式时遇到了困难。
我在注释代码中包含了如何使用 Vanilla JS 设置地图样式,但在 React 中不断出现错误。
const googleMapRef = useRef(null);
const googleMap = useRef(null);
const marker = useRef(null);
const createGoogleMap = () =>
new window.google.maps.Map(googleMapRef.current, {
center: {
lat: userLocation.lat,
lng: userLocation.lng,
},
zoom: 16,
disableDefaultUI: true,
gestureHandling: 'none',
mapTypeControlOptions: {
mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain', 'map'],
},
});
const createMarker = () =>
new window.google.maps.Marker({
position: { lat: userLocation.lat, lng: userLocation.lng },
map: googleMap.current,
icon: {
path: window.google.maps.SymbolPath.CIRCLE,
scale: 5,
fillColor: '#1652f0',
fillOpacity: 1,
strokeColor: '#1652f0',
strokeWeight: 8,
strokeOpacity: 0.5,
},
});
useEffect(() => {
const googleMapScript = document.createElement('script');
googleMapScript.src = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAP_API_KEY}`;
window.document.body.appendChild(googleMapScript);
googleMapScript.addEventListener('load', () => {
googleMap.current = createGoogleMap();
marker.current = createMarker();
});
}, []);
const mapStyles = () =>
new window.google.maps.StyledMapType(
[
{
elementType: 'geometry',
stylers: [
{
color: '#f5f5f5',
},
],
},
...
],
{ name: 'Map' }
);
// createGoogleMap.mapTypes.set('map', mapStyles); <-- This is how you would normally bind the styles to the map in Vanilla JS but can't seem to do it in React
// map.setMapTypeId('folded_map');
return (
<div>
<div id="map" ref={googleMapRef} style={divStyles} />
</div>
);
解决方案
谷歌地图样式器:https ://mapstyle.withgoogle.com/
使用谷歌地图进行反应:google-maps-react
npm install --save google-maps-react
将样式添加到 GoogleMap 组件
<GoogleMap
options={{
styles: [...]
}}
/>
推荐阅读
- javascript - 即使使用索引,复合查询也不起作用
- wordpress - 我应该在谷歌云平台上为 wordpress 多站点 woocommerce 和哪个引擎安装哪个应用程序?
- python - 列向量和矩阵的区别
- python - 我不能乘以 python 中的浮点数?
- javascript - 如果输入:8-e 预期输出:2|4|6|8
- sql - 加载大数据时的 ColdFusion 和加载消息
- android - 将 Drawable 资源转换为位图
- c++ - wxWidgets 适合 wxFlexGridSizer 中的大 wxGrid
- symfony - 为什么我会看到 CheckMX 已弃用警告?
- beanshell - 如何在 csv 文件中为 bean shell 脚本中保存的变量添加标题?