Bootstrap

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 API
      navigator.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 />

          <Button
            style={{ 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;

;