react中使用谷歌地图并定位
生活随笔
收集整理的這篇文章主要介紹了
react中使用谷歌地图并定位
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
react中使用谷歌地圖
1、引入
index.html文件中引入谷歌地圖
<!DOCTYPE html> <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="shrink-to-fit=no"><meta name="theme-color" content="#000000"><link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"><title>OMS</title><script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDVTk78W-PvhqUC08l6MBqUHTjJXSGcP4g&libraries=places&language="></script></head><body><div id="root"></div></body> </html>2、使用
import React, { Component } from "react"; import { Button, Input } from "antd"; import { FormattedMessage } from "react-intl";const googleMap = window.google && window.google.maps;class Map extends Component {constructor(props) {super(props);this.state = {map: null,lat: null,lng: null,marker: [],};}// 初始化谷歌地圖componentDidMount() {if ("geolocation" in navigator) {//檢測當前設備是否支持H5Geolocation APInavigator.geolocation.getCurrentPosition((position) => {let mapProp = {center: new googleMap.LatLng(position.coords.latitude, position.coords.longitude),zoom: 17,mapTypeId: googleMap.MapTypeId.ROADMAP,};let map = new googleMap.Map(document.getElementById("googleMap"), mapProp);if (this.state.marker[0] && this.state.marker[0].setMap) {this.state.marker[0].setMap(null);}const arr = [];arr[0] = new googleMap.Marker({position: new googleMap.LatLng(position.coords.latitude, position.coords.longitude),});this.setState({marker: arr,lat: position.coords.latitude,lng: position.coords.longitude,map,},() => {this.state.marker[0].setMap(map);});});} else {alert("該瀏覽器不支持獲取地理位置");}}addMap = () => {googleMap.event.addListener(this.state.map, "click", (e) => {if (this.state.marker[0] && this.state.marker[0].setMap) {this.state.marker[0].setMap(null);}const arr = [];arr[0] = new googleMap.Marker({position: new googleMap.LatLng(e.latLng.lat(), e.latLng.lng()),});this.setState({marker: arr,lat: e.latLng.lat(),lng: e.latLng.lng(),},() => {this.state.marker[0].setMap(this.state.map);});});};render() {return (<div><div style={{ display: "flex", alignItems: "center", marginBottom: 10 }}><span><FormattedMessage id="lng" />:</span><Input style={{ width: "200px" }} value={this.state.lng} disabled /><span style={{ marginLeft: 20 }}><FormattedMessage id="lat" />:</span><Input style={{ width: "200px" }} value={this.state.lat} disabled /><Buttonstyle={{ marginLeft: 20 }}type="primary"onClick={() => {this.props.addLatLng(this.state.lat, this.state.lng);this.props.onCancel();}}><FormattedMessage id="ok" /></Button></div><div id="googleMap" style={{ width: "900px", height: "500px" }} onClick={this.addMap}></div>;</div>);} }export default Map;總結
以上是生活随笔為你收集整理的react中使用谷歌地图并定位的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 人工智能文本生成器将如何影响写作行业
- 下一篇: Linux.2- shell命令(部分)