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

亲测有效~ ❤️

相关推荐
古一|23 分钟前
Vue3中ref与reactive实战指南:使用场景与代码示例
开发语言·javascript·ecmascript
peachSoda725 分钟前
封装一个不同跳转方式的通用方法(跳转外部链接,跳转其他小程序,跳转半屏小程序)
前端·javascript·微信小程序·小程序
@PHARAOH37 分钟前
HOW - 浏览器兼容(含 Safari)
前端·safari
undefined在掘金390411 小时前
flutter 仿商场_首页
前端
少卿1 小时前
react-native图标替换
前端·react native
熊猫钓鱼>_>1 小时前
TypeScript前端架构与开发技巧深度解析:从工程化到性能优化的完整实践
前端·javascript·typescript
JYeontu2 小时前
肉眼难以分辨 UI 是否对齐,写个插件来辅助
前端·javascript
fox_2 小时前
别再踩坑!JavaScript的this关键字,一次性讲透其“变脸”真相
前端·javascript
盛夏绽放2 小时前
uni-app Vue 项目的规范目录结构全解
前端·vue.js·uni-app
少卿2 小时前
React Native Vector Icons 安装指南
前端·react native