reactjs - 如何在 React 中使用 @googlemaps/js-api-loader?
问题描述
我想在 React 中使用 Google Maps API。
我读了这篇文章,发现最近发布了一些软件包。
但即使我看这个例子我也不知道。
如何在 React 中使用谷歌地图?我想拿个记号笔,换个记号笔图标。
请帮我...
解决方案
绝对了解有一些包可以帮助您加载 Google Map 和 Javascript API,例如
我以前使用google-map-react
过,但现在我需要一种更灵活的方式来加载 Google Maps JavaScript API 脚本。
对于像我这样通过搜索如何@googlemaps/js-api-loader
在 React 中使用而来到这里的人,这里有一些代码示例。
- 安装 npm 包:
npm i @googlemaps/js-api-loader
- 代码示例:
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>
)
}
}
推荐阅读
- typescript - 如何在角度材料 2 中使用 mat-chip 和自动完成来保存选定的对象
- jenkins - 在 Jenkins 管道中使用 Groovy 创建一个包含一些内容的文件
- c# - Parent 不包含带 0 个参数的构造函数
- complexity-theory - 在复杂度类 P 中,接受=决定。为什么不是NP?
- excel - Excel条码描述查找
- python - Python Tkinter 发布事件
- java - 在 Inno Setup 中查找 JRE 安装路径
- javascript - 使用新数组更新 React State
- laravel - BelongsTo 类的 create 方法在哪里?
- c# - Xamarin Android 应用程序在 Galaxy Note 8 上崩溃