首页 > 解决方案 > 如何在 React 中使用 @googlemaps/js-api-loader?

问题描述

我想在 React 中使用 Google Maps API。

我读了这篇文章,发现最近发布了一些软件包。

但即使我看这个例子我也不知道。

如何在 React 中使用谷歌地图?我想拿个记号笔,换个记号笔图标。

请帮我...

标签: reactjsgoogle-maps

解决方案


绝对了解有一些包可以帮助您加载 Google Map 和 Javascript API,例如

我以前使用google-map-react过,但现在我需要一种更灵活的方式来加载 Google Maps JavaScript API 脚本。

对于像我这样通过搜索如何@googlemaps/js-api-loader在 React 中使用而来到这里的人,这里有一些代码示例。

  1. 安装 npm 包: npm i @googlemaps/js-api-loader
  2. 代码示例:
import React, { Component } from 'react';
import { Loader } from '@googlemaps/js-api-loader';

const loader = new Loader({
    apiKey: "YOUR_API_KEY"
    version: "weekly",
    libraries: ["places"]
});

export default class DemoComponent extends Component {
    constructor(props) {
        super(props);
        this.state = {};
    }

    componentDidMount() {
        let self = this;
        const defaultMapOptions = {
            center: {
                lat: 40.762312,
                lng: -73.979345
            },
            zoom: 11
        };
        loader.load().then((google) => {
            const map = new google.maps.Map(
                self.googleMapDiv,
                defaultMapOptions);
            /*
                store them in the state so you can use it later
                E.g. call a function on the map object:
                    this.state.map.panTo(...)
                E.g. create a new marker:
                    new this.state.google.maps.Marker(...)
            */
            this.setState({
                google: google,
                map: map
            });
        });
    }

    render() {
        return (
            <div
                ref={(ref) => { this.googleMapDiv = ref }}
                style={{ height: '100vh', width: '100%' }}>
            </div>
        )
    }
}

推荐阅读