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

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

cpp 复制代码
"@react-google-maps/api": "^2.19.3",

2.加入项目中

cpp 复制代码
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 = ''; //申请的谷歌key
        return (
            <div style={{ height: '400px', width: '100%' }}>
                <LoadScript googleMapsApiKey={googleKey}>
                    <GoogleMap
                        mapContainerStyle={{ 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:;";

亲测有效~ ❤️

相关推荐
fthux1 小时前
RenoPit 能为普通业主做什么?看懂图纸、审查合同,提前发现装修坑
javascript·人工智能·ai·开源·github·chrome扩展·open source·edge扩展·firefox扩展
仿生狮子2 小时前
✂️ Nuxt 最简单的字体裁剪工具:Fontize
javascript·vue.js·nuxt.js
石小石Orz5 小时前
我发现了开发者AI产品营收的新方向
前端·虚拟现实
老马识途2.05 小时前
关于跨域问题的总结
java·前端
魔力女仆6 小时前
分享一个 JS 鼠标跟随贪吃蛇背景库
开发语言·javascript·计算机外设
别惊醒渔人7 小时前
Vue3 Diff 优化:最长递增子序列 LIS
前端·javascript·vue.js
颜酱7 小时前
07 | 把字段与指标同步到 Qdrant(生成阶段)
前端·人工智能·后端
用户059540174467 小时前
把AI长期记忆测试从手动验证换成pytest,2天揪出11个隐藏Bug
前端·css
Larcher8 小时前
从“加载模型”界面到端侧推理:拆解一个 React + WebGPU 大模型 Demo
javascript·后端
Larcher8 小时前
从状态快照到惰性初始化:读懂 React useState 的三个关键场景
javascript·人工智能·后端