Webpack项目中加载Google Maps Geometry Library遇问题求助
解决Webpack项目中加载Google Maps Geometry Library的问题
核心解决方案:在API加载配置中添加libraries参数
你之前未在load-google-maps-api的配置里指定要加载的几何库,这就是基础功能正常但Geometry库无法使用的原因。只需在调用loadGoogleMapsApi时,把libraries: ['geometry']加入配置对象即可。
为什么spherical-geometry-js会报错?
这个库依赖全局的google.maps对象,但你可能在Google Maps API完全加载完成前就引用了它,或者未确保API已正确加载几何模块,导致找不到spherical属性。直接使用Google Maps官方的Geometry库更可靠。
修改后的完整代码
const loadGoogleMapsApi = require('load-google-maps-api'); var map; class Map { static loadGoogleMapsApi() { // 添加libraries参数指定加载geometry库 return loadGoogleMapsApi({ key: '****', libraries: ['geometry'] }); } static createMap(googleMaps) { var mapOptions = { center: { lat: 40.7484405, lng: -73.9944191 }, zoom: 12 }; $('#map').each(function() { map = new googleMaps.Map($(this)[0], mapOptions); }); // 示例:使用Geometry库的computeDistanceBetween方法 const point1 = new googleMaps.LatLng(40.7484405, -73.9944191); const point2 = new googleMaps.LatLng(40.7584405, -73.9844191); const distance = googleMaps.geometry.spherical.computeDistanceBetween(point1, point2); console.log('两点距离:', distance); } } Map.loadGoogleMapsApi().then(function(googleMaps) { Map.createMap(googleMaps); });
注意事项
libraries是数组格式,可同时指定多个库(比如['geometry', 'places'])- 所有Geometry库的方法都要在
googleMaps对象加载完成后调用,也就是在then回调或createMap方法内部使用
内容的提问来源于stack exchange,提问作者Tekimoto
相关产品推荐
相关产品推荐

