使用ng-map自定义Google Maps标记时出现Cannot read property 'lng' of undefined错误
解决ng-map中custom-marker更新位置时的"Cannot read property 'lng' of undefined"错误
我之前在使用ng-map的自定义标记时也踩过这个坑,很清楚这个错误的根源😎
错误原因
问题出在custom-marker的position属性绑定方式上:
- 原生的
<marker>标签内部做了兼容处理,能把你用{{}}插值生成的字符串(比如"39.9042,116.4074")自动解析成Google Maps的LatLng对象; - 但
<custom-marker>没有这个自动解析逻辑,它要求position必须是一个包含lat和lng属性的JS对象,或者直接是google.maps.LatLng实例。你用{{p.Location.position}}插值后,传递给它的是一个字符串,当ng-map尝试读取这个字符串的lng属性时,自然就会抛出"Cannot read property 'lng' of undefined"的错误。
解决方案
分两步修改:
1. 确保位置数据是对象格式
首先在JS代码中,把位置转换成包含lat和lng的对象(如果后端返回的是字符串格式的话):
// 假设device.Location.position是类似"39.9042,116.4074"的字符串 const [lat, lng] = device.Location.position.split(',').map(Number); // 存储为对象格式 page.watchpath[deviceindex] = { position: { lat, lng }, // 或者用google.maps.LatLng实例:new google.maps.LatLng(lat, lng) ImagePath: imagePath };
如果你的device.Location.position已经是{lat: xxx, lng: xxx}的对象,这一步可以跳过。
2. 修改custom-marker的绑定方式
去掉position属性的插值语法,直接绑定表达式:
<custom-marker ng-repeat="p in page.watchpath track by $index" position="p.Location.position"> <div> <img src="{{p.ImagePath ? page.serviceBasePath + p.ImagePath.substr(2) : page.serviceBasePath + 'Images/avatar.jpg'}}" style="border-radius: 50%; height:40px;width:40px;" /> </div> </custom-marker>
这样Angular会直接把p.Location.position这个对象传递给custom-marker,而不是转换成字符串,ng-map就能正确读取lat和lng属性了。
验证
当你更新page.watchpath[deviceindex].position时,确保它始终是有效的位置对象(不是字符串),此时custom-marker就能正常更新位置,不会再出现报错啦。
内容的提问来源于stack exchange,提问作者chaitanya k
相关产品推荐
相关产品推荐

