我想尝试使用谷歌地图API来显示地图,但我想知道是否有更好的方法来加载标记而不是将它放在我的index.html中.
我希望脚本只在我去/map
路线时加载.所以,我想从我的移除它index.html
并动态加载它.但是,我还想确保如果已经加载了我不再尝试加载它.
我不确定是否有一个库来处理这个问题.到目前为止我尝试过(但失败了)的是创建一个loadScript
函数,它将一个附加到实际的dom并为它分配一个键,所以在这种情况下
'google-maps
.
谢谢
这就是我在最近的项目中所做的工作.我使用了react-async-script-loader组件.
import React from 'react'; import scriptLoader from 'react-async-script-loader'; class Maps extends React.Component { constructor(props) { super(props); this.map = null; } componentWillReceiveProps({ isScriptLoaded, isScriptLoadSucceed }) { if (isScriptLoaded && !this.props.isScriptLoaded) { // load finished if (isScriptLoadSucceed) { this.map = new google.maps.Map(this.refs.map, { center: { lat: 10.794234, lng: 106.706541 }, zoom: 20 }); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( position => { const pos = { lat: position.coords.latitude, lng: position.coords.longitude }; this.map.setCenter(pos); const marker = new google.maps.Marker({ position: pos, map: this.map, title: 'Hello World!' }); }, () => { console.log('navigator disabled'); } ); } else { // Browser doesn't support Geolocation console.log('navigator disabled'); } } else this.props.onError(); } } render() { return ({!this.map &&); } } export default scriptLoader(['https://maps.googleapis.com/maps/api/js?key=API_KEY'])(Maps);Loading...}
谢谢阮清。就像google
现在在全球范围内使用的那样window.google
。
import React, { Component } from 'react'; import scriptLoader from 'react-async-script-loader'; class Map extends Component{ constructor(props) { super(props); } componentWillReceiveProps({isScriptLoadSucceed}){ if (isScriptLoadSucceed) { var markers = []; var map = new window.google.maps.Map(document.getElementById('map'), { zoom: 12, center: {lat: 37.7749300, lng: -122.4194200} }); } else{ alert("script not loaded") } } render(){ return() } } export default scriptLoader( ["https://maps.googleapis.com/maps/api/js?key= APIKEY"] )(Map)
使用react钩子我们还可以加载外部脚本
https://usehooks.com/useScript/
//useScript custom hooks from the site let cachedScripts = []; function useScript(src) { // Keeping track of script loaded and error state const [state, setState] = useState({ loaded: false, error: false }); useEffect( () => { // If cachedScripts array already includes src that means another instance ... // ... of this hook already loaded this script, so no need to load again. if (cachedScripts.includes(src)) { setState({ loaded: true, error: false }); } else { cachedScripts.push(src); // Create script let script = document.createElement("script"); script.src = src; script.async = true; // Script event listener callbacks for load and error const onScriptLoad = () => { setState({ loaded: true, error: false }); }; const onScriptError = () => { // Remove from cachedScripts we can try loading again const index = cachedScripts.indexOf(src); if (index >= 0) cachedScripts.splice(index, 1); script.remove(); setState({ loaded: true, error: true }); }; script.addEventListener("load", onScriptLoad); script.addEventListener("error", onScriptError); // Add script to document body document.body.appendChild(script); // Remove event listeners on cleanup return () => { script.removeEventListener("load", onScriptLoad); script.removeEventListener("error", onScriptError); }; } }, [src] // Only re-run effect if script src changes ); return [state.loaded, state.error]; }
用法
//App.js import React from "react"; import ReactDOM from "react-dom"; import { useState, useEffect } from "react"; function App() { const [loaded, error] = useScript( "https://maps.googleapis.com/maps/api/js?key=API_KEY" ); useEffect(() => { if (loaded) { new window.google.maps.Map(document.getElementById("map"), { zoom: 12, center: { lat: 37.77493, lng: -122.41942 } }); } }, [loaded]); return (); }Script loaded: {loaded.toString()}