@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:;";

亲测有效~ ❤️

相关推荐
恋猫de小郭3 小时前
Flutter Zero 是什么?它的出现有什么意义?为什么你需要了解下?
android·前端·flutter
崔庆才丨静觅10 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby606110 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了10 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅10 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅11 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅11 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment11 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅12 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊12 小时前
jwt介绍
前端