react使用高德api出现一个bug ,下面是代码和报错信息,情况是初始化时正常,刷新页面就会报错
刷新的时候有可能地图没有加载完成
AMap.plugin("AMap.DistrictSearch", () => {
// 创建行政区查询对象
let district = new AMap.DistrictSearch({
extensions: "all", // 设置查询行政区级别为区
level: "district"
});
// 指定查询的行政区域名称或区域编码
let districtName = "浦东新区";
// 查询行政区边界信息
district.search(districtName, (status, result) => {
if (status === "complete" && result.districtList.length > 0) {
// 获取边界信息
let bounds = result.districtList[0].boundaries;
if (bounds) {
// 构造多边形的路径
let polygonPath = [];
for (let i = 0; i < bounds.length; i += 1) {
polygonPath[i] = bounds[i];
}
// 构造多边形对象
let polygon = new AMap.Polygon({
path: polygonPath,
strokeWeight: 5,
fillOpacity: 0.4,
fillColor: "#80d8ff",
strokeColor: "#91ea"
});
// 等待地图对象完全初始化完成后再添加多边形
amap.on('complete', () => {
// 添加多边形到地图上
amap.add(polygon);
// 调整地图视图以适应多边形
amap.setFitView(polygon);
});
} else {
console.log("未获取到边界信息");
}
} else {
console.log("查询行政区失败");
}
});
});
先在最上面解构出来location
看官方Api文档改成