@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 = ''; //申请的谷歌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:;”;

亲测有效~ ❤️

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-09 22:30:03       49 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-09 22:30:03       53 阅读
  3. 在Django里面运行非项目文件

    2024-07-09 22:30:03       42 阅读
  4. Python语言-面向对象

    2024-07-09 22:30:03       53 阅读

热门阅读

  1. CUDA Kernel调试与优化--背景知识扫盲(LLM生成)

    2024-07-09 22:30:03       14 阅读
  2. C语言希尔排序详解与实例

    2024-07-09 22:30:03       19 阅读
  3. 多尺度旋转编码

    2024-07-09 22:30:03       18 阅读
  4. PostgreSQL的使用

    2024-07-09 22:30:03       16 阅读
  5. 定投就像还房贷

    2024-07-09 22:30:03       19 阅读
  6. Linux下python抓取动态网页内容

    2024-07-09 22:30:03       22 阅读
  7. uniapp中 uni.previewImage用法

    2024-07-09 22:30:03       18 阅读
  8. JVM专题之走进类加载

    2024-07-09 22:30:03       18 阅读
  9. 大模型/NLP/算法面试题总结

    2024-07-09 22:30:03       21 阅读
  10. 数据结构之B树

    2024-07-09 22:30:03       15 阅读