欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 明星 > @react-google-maps/api实现谷歌地图嵌入React项目中,并且做到点击地图任意一处,获得它的经纬度

@react-google-maps/api实现谷歌地图嵌入React项目中,并且做到点击地图任意一处,获得它的经纬度

2024/10/26 0:30:34 来源:https://blog.csdn.net/weixin_43517190/article/details/140184022  浏览:    关键词:@react-google-maps/api实现谷歌地图嵌入React项目中,并且做到点击地图任意一处,获得它的经纬度

1.第一步要加入项目package.json中或者直接yarn install它都可以

"@react-google-maps/api": "^2.19.3",

2.加入项目中

import AMapLoader from '@amap/amap-jsapi-loader';import React, { PureComponent } from 'react';
import { GoogleMap, LoadScript, Marker } from '@react-google-maps/api';interface ScalSelectStates {/*** 当前选择位置经纬度*/centerPosition: any[];
}export class ScalSelect extends PureComponent<{}, ScalSelectStates> {constructor(props: any) {super(props);this.state = {centerPosition: [116.409969,39.982387],};}//谷歌地图点击方法handleGoogleClick = (event: any) => {if (event && event.latLng) {const centerPosition = [event.latLng.lng().toFixed(6), event.latLng.lat().toFixed(6)];this.setState({centerPosition,});}};render() {const {centerPosition} = this.state;const lng = Number(centerPosition[0]);const lat = Number(centerPosition[1]);const googleKey = ''; //申请的谷歌keyreturn (<div style={{ height: '400px', width: '100%' }}><LoadScript googleMapsApiKey={googleKey}><GoogleMapmapContainerStyle={{ width: '100%', height: '400px' }}zoom={11}center={{ lat, lng }}onClick={this.handleGoogleClick}><Marker position={{ lat, lng }} /></GoogleMap></LoadScript></div>)}
}

附上效果图一张
在这里插入图片描述

希望对大家有帮助~❤️

温馨提示!!!:在自己开发环境可以正常渲染,然后正式部署到环境上的时候渲染不出来,有个错误提示
在这里插入图片描述

解决方式是:找后端人员
设置Content-Security-Policy 允许可以要加载的外部脚本 add_header Content-Security-Policy “script-src ‘self’ https://maps.googleapis.com ‘unsafe-inline’ ‘unsafe-eval’ blob: data:;”;

亲测有效~ ❤️

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com