当前位置: 首页 > news >正文

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

亲测有效~ ❤️

http://www.lryc.cn/news/394490.html

相关文章:

  • 【MySQL】2.库的操作
  • 深入Laravel服务容器:构建灵活应用的秘诀
  • 3.js - 模板渲染 - 金属切面效果
  • 【测试】系统压力测试报告模板(Word原件)
  • 图片预加载和懒加载
  • Java中的数据可视化与图表库选择
  • STM32-TIM定时器
  • Python OpenCV与霍夫变换:检测符合特定斜率范围的直线
  • ubuntu22.04+pytorch2.3安装PyG图神经网络库
  • 新型开发语言的试用感受-仓颉语言发布之际
  • 基于字典学习的地震数据降噪(MATLAB R2021B)
  • 【Web】
  • kafka-3
  • MySQL性能优化 二、表结构设计优化
  • 用HttpURLConnection复现http响应码405
  • 2-27 基于matlab的一种混凝土骨料三维随机投放模型
  • ISA95-Part4-业务流程的解析与设计思路
  • 【Spring Cloud】一个例程快速了解网关Gateway的使用
  • 仿哔哩哔哩视频app小程序模板源码
  • 数据库存储引擎
  • 【单片机毕业设计选题24049】-基于STM32单片机的智能手表设计
  • 利用面向AWS的Thales Sovereign解决方案保护AI之旅
  • 学习笔记——交通安全分析13
  • PHP-实例-文件上传
  • LeetCode刷题之HOT100之完全平方数
  • 【SpringCloud应用框架】Nacos集群架构说明
  • JS进阶-作用域
  • stm32 使用GPIO模拟串口发送
  • 数据的统计探针:SKlearn中的统计分析方法
  • 实例演示Kafka-Stream消息流式处理流程及原理