Bing Maps V8多边形地理围栏坐标提取空数组问题求助
问题分析与解决方案
核心问题排查
你遇到的空数组问题,大概率是以下几个原因导致:
- Polygon顶点未正确同步:mousedown时添加的坐标没有更新到Polygon实例的
locations属性中 - 事件绑定时机错误:地图未完全初始化就绑定了事件监听器,导致点击事件无法触发坐标收集
- 坐标获取逻辑依赖失效:
LocationRect.fromLocations()需要Polygon已有有效顶点,若Polygon本身无坐标,自然返回空边界
修复后的实现代码
import React, { useEffect, useRef, useState } from 'react'; const BingMapPolygonDrawer = () => { const mapRef = useRef(null); const polygonRef = useRef(null); const [drawing, setDrawing] = useState(false); const [polygonLocations, setPolygonLocations] = useState([]); useEffect(() => { if (!window.Microsoft) return; // 初始化地图实例 const map = new window.Microsoft.Maps.Map(mapRef.current, { credentials: '你的Bing Maps密钥', center: new window.Microsoft.Maps.Location(47.6062, -122.3321), zoom: 12 }); // 创建初始空多边形 polygonRef.current = new window.Microsoft.Maps.Polygon([], { fillColor: 'rgba(0, 255, 0, 0.5)', strokeColor: '#000000', strokeThickness: 2 }); map.entities.push(polygonRef.current); // 绑定鼠标按下事件:记录顶点并更新多边形 window.Microsoft.Maps.Events.addHandler(map, 'mousedown', (e) => { if (!e.location) return; setDrawing(true); const newLocations = [...polygonLocations, e.location]; setPolygonLocations(newLocations); // 同步更新多边形的顶点集合 polygonRef.current.setLocations(newLocations); }); // 绑定鼠标抬起事件:结束绘制并输出坐标 window.Microsoft.Maps.Events.addHandler(map, 'mouseup', () => { if (!drawing) return; setDrawing(false); // 直接获取多边形的所有顶点坐标 const coords = polygonRef.current.getLocations().map(loc => ({ latitude: loc.latitude, longitude: loc.longitude })); console.log('Submitting geofence with coordinates:', coords); }); // 组件卸载时清理资源 return () => { window.Microsoft.Maps.Events.removeHandler(map, 'mousedown'); window.Microsoft.Maps.Events.removeHandler(map, 'mouseup'); map.entities.clear(); }; }, [polygonLocations]); return ( <div ref={mapRef} style={{ width: '100%', height: '600px' }} /> ); }; export default BingMapPolygonDrawer;
关键修复点说明
- 顶点同步机制:每次点击后通过
polygon.setLocations()将新坐标同步到Polygon实例,确保实例始终持有最新的顶点数据 - 事件绑定时机:在地图初始化完成后再绑定事件监听器,避免无效绑定导致的坐标收集失败
- 坐标获取逻辑:直接调用
polygon.getLocations()获取完整的多边形顶点数组;若确实需要边界框,可在获取有效顶点后再用LocationRect.fromLocations(polygon.getLocations())计算
内容的提问来源于stack exchange,提问作者AYESIGA OWEN
相关产品推荐
相关产品推荐

