高德地图-当默认打开InfoWindow信息窗体时,setCenter()无法居中

文章讲述了开发者在使用高德地图API时遇到的问题,即点击坐标后infoWindow信息窗体无法自动定位到坐标中心。通过调整代码顺序,将设置地图中心的代码置于信息窗体打开之前解决了这个问题,推测原因是渲染周期问题。
摘要由CSDN通过智能技术生成

最近在研究地图的 API,对比了一下 高德地图百度地图,最后选择了高德地图。在开发遇到点小问题,记录一下。

背景

需求功能是,点击任意(维护的)坐标后,跳转到该坐标,并以该坐标为中心,并且默认显示该地址 MarkerinfoWindow 信息窗体。

问题是,当点击任意坐标后, infoWindow 信息窗体可以默认打开,但是无法将地图中心设置为当前 Marker 的坐标,位置无法居中。用户体验十分不好。

解决方案

问题代码:

const onSelect = (position: number[], title: string) => {  
  const content = `  
    <div style="width: fit-content; padding: 4px; text-align: center;">  
      <b>${title}</b>  
      <br/>  
      <br/>  
      坐标:[${position[0]}, ${position[1]}]  
    </div>`;  
  // 设置坐标为屏幕中心
  map.setCenter(position);  
  const marker = new AMap.Marker({  
    position: position  
  });  
  const infoWindow = new AMap.InfoWindow({  
    isCustom: false, 
    content: content,  
    offset: new AMap.Pixel(0, -35)  
  });  
  
  map.add(marker);  
  // 显示信息窗体
  infoWindow.open(map, new AMap.LngLat(...position));  
  // 信息窗体点击事件
  marker.on('click', (e: any) => infoWindow.open(map, e.target.getPosition()));  
};

解决方案:

const onSelect = (position: number[], title: string) => {  
  const content = `  
    <div style="width: fit-content; padding: 4px; text-align: center;">  
      <b>${title}</b>  
      <br/>  
      <br/>  
      坐标:[${position[0]}, ${position[1]}]  
    </div>`;  
  
  const marker = new AMap.Marker({  
    position: position  
  });  
  const infoWindow = new AMap.InfoWindow({  
    isCustom: false, 
    content: content,  
    offset: new AMap.Pixel(0, -35)  
  });  
  
  map.add(marker);  
  // 显示信息窗体
  infoWindow.open(map, new AMap.LngLat(...position));  
  // 信息窗体点击事件
  marker.on('click', (e: any) => infoWindow.open(map, e.target.getPosition()));  
  // 设置坐标为屏幕中心
  map.setCenter(position);
};

infoWindow 信息窗体代码放在设置坐标中心的上面即可

猜测渲染周期导致

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值