RI 正在与 CRA React 项目合作。在 React 组件中,我尝试导入和加载外部 Azure Map 独立脚本,例如 azure-maps-geolocation-control.js,它添加到 Azure Map 命名空间(atlas)。在此 React 组件中,我导入了 Azure Map SDK(如 azure-maps-control),它可以很好地渲染地图并提供命名空间。
在地图就绪事件下,我尝试实例化 GeolocationControl 对象,但似乎脚本无法读取地图集名称空间。该外部脚本放置在 public 文件夹中,并动态放置在 index.html 中。
如何在 React 组件中使脚本链接到 Azure Map SDK 命名空间?谢谢你
import React, { useEffect, useRef, useState } from 'react';
import atlas from 'azure-maps-control';
const Map = () => {
const mapContainerRef = useRef(null);
useEffect(() => {
const map = new atlas.Map(mapContainerRef.current, {
center: [103.852, 1.290],
zoom: 15,
view: 'Auto',
authOptions: {
authType: 'subscriptionKey',
subscriptionKey: 'my-sub-key'
}
})
map.events.add('ready', async function () {
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/lib/azure-maps-geolocation-control.js`;
script.type = 'text/javascript';
script.async = true;
document.head.appendChild(script);
map.controls.add([
new atlas.control.ZoomControl(),
new atlas.control.CompassControl(),
new atlas.control.PitchControl(),
new atlas.control.GeolocationControl({
style: 'auto'
})
], {
position: "top-left"
});
})
return () => {
map.dispose();
};
}, []);
return (
<>
<div ref={mapContainerRef} style={{ height: "100%", width: "100%" }}></div>
</>
);
};
export default Map;
我尝试导入Azure Map SDK(azure-maps-control)并正确初始化地图。然后动态地将外部 Azure Map 脚本 (azure-maps-geolocation-control.js) 添加到 index.html 中的地图就绪事件下。
期望脚本与 SDK 集成,但似乎无法读取/合并 SDK 中的 atlas 命名空间。
将外部 Azure Map 脚本 (
azure-maps-geolocation-control.js
) 与 React 组件中的 Azure Map SDK 命名空间 (atlas
) 集成
azure-maps-control
),并在地图准备好后动态加载外部Azure Map脚本(azure-maps-geolocation-control.js
)。atlas
命名空间并在地图就绪事件处理程序中实例化 GeolocationControl
对象。import React, { useEffect, useRef } from 'react';
import atlas from 'azure-maps-control';
const Map = () => {
const mapContainerRef = useRef(null);
useEffect(() => {
const initMap = async () => {
const map = new atlas.Map(mapContainerRef.current, {
center: [103.852, 1.290],
zoom: 15,
view: 'Auto',
authOptions: {
authType: 'subscriptionKey',
subscriptionKey: 'my-sub-key'
}
});
map.events.add('ready', async () => {
// Dynamically load the external Azure Map script
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/lib/azure-maps-geolocation-control.js`;
script.type = 'text/javascript';
script.async = true;
// Ensure that the script is loaded after the Azure Map SDK
script.onload = () => {
// Instantiate the GeolocationControl object after the script is loaded
new atlas.control.GeolocationControl({
style: 'auto'
}).addTo(map);
};
document.head.appendChild(script);
});
return () => {
map.dispose();
};
};
initMap();
}, []);
return (
<div ref={mapContainerRef} style={{ height: '100vh', width: '100%' }} />
);
};
export default Map;
useEffect
初始化地图并在地图准备好后动态加载外部脚本,异步加载外部脚本,并且onload
回调确保只有在脚本完全加载后才实例化GeolocationControl
对象.GeolocationControl
方法将 addTo
对象添加到地图中。npm i azure-maps-control