Angular中使用经纬度渲染Google Map出现坐标无效报错的问题咨询
解决Angular Google Map的InvalidValueError报错问题
报错原因
你当前的代码里,position是在类初始化阶段直接赋值的,但this.property的数据是通过this.route.data.subscribe异步获取的——类初始化时this.property还未被赋值(处于undefined状态),所以parseFloat(this.property.lat)会得到NaN,导致Google Map无法识别无效坐标,触发报错。
修复步骤
- 初始化position为合法默认值
先把position初始化为包含有效坐标的对象,避免初始加载时出现无效值。 - 在数据获取完成后赋值position
等route.data的回调函数拿到this.property数据后,再计算并赋值position,确保此时lat和lng是有效的字符串。 - 添加空值校验(推荐)
对this.property.lat和this.property.lng做空值检查,避免数据异常时再次出现NaN。
修改后的TypeScript代码示例
import { Component, OnInit } from '@angular/core'; // 引入你需要的其他依赖 @Component({ // 组件元数据 }) export class YourComponent implements OnInit { public zoom = 15; // 初始化position为合法默认坐标 public position = { lat: 0, lng: 0 }; property: any; // 确保已声明该变量 // 其他属性... ngOnInit() { this.form.controls['subject'].disable(); this.token = localStorage.getItem('token'); this.propertyId = +this.route.snapshot.params['id']; this.route.data.subscribe((data: any) => { this.property = data['prp']; // 拿到有效数据后再赋值position,添加空值校验 if (this.property?.lat && this.property?.lng) { this.position = { lat: parseFloat(this.property.lat), lng: parseFloat(this.property.lng) }; } else { // 可选:处理数据缺失的情况,设置默认坐标 this.position = { lat: 24.488354, lng: 54.3951 }; } }); this.propid = this.propertyId; this.propidStr = "nums" + this.propid.toString(); let data2:any = localStorage.getItem(this.propidStr); this.likes = JSON.parse(data2); } }
额外注意点
- 可以在
route.data的回调里添加console.log(this.property),确认是否拿到了正确的JSON数据。 - 确保
position的类型符合Angular Google Maps要求的{lat: number, lng: number}格式。
内容的提问来源于stack exchange,提问作者Shahed RTW
相关产品推荐
相关产品推荐

