将 Marker Pin 保持在中心位置,我将拖动地图

Keep Marker Pin in center will I drag map

我正在构建一个用例,其中我使用 google 地图 API 使用 IONIC 框架。

在页面中显示带有位置 (lat,lng) 标记针的地图后,我需要允许用户拖动地图,保持针固定,以便他们可以在拖动时精确定位他们的地址停止,我需要获取该点的纬度、经度并获取该点的地址并显示在 UI 中。我怎样才能做到这一点?

以下是我用来显示带有 PIN 码的地图的代码。

  ngAfterContentInit(): void {

this.map = new google.maps.Map(
  this.mapNativeElement.nativeElement,
  {
    center: { lat: 17.455841, lng: 78.335507 },
    zoom: 16,
    disableDefaultUI: true
  }
);

this.marker = new google.maps.Marker(
  {
    map: this.map,
    draggable: true,
    animation: google.maps.Animation.DROP,
    position: { lat: 17.455841, lng: 78.335507 }
  });

你可以试试这个:

this.marker = new google.maps.Marker(
{
  map: this.map,
  draggable: true,
  animation: google.maps.Animation.DROP,
  position: { lat: 17.455841, lng: 78.335507 }
});

google.maps.event.addListener(myMarker, 'dragend', () => {
    this.map.setCenter(this.map.getPosition()); 
});

google.maps.event.addListener(map, 'drag', function () {
    myMarker.setPosition(this.getCenter()); 
});

google.maps.event.addListener(map, 'dragend', function () {
    myMarker.setPosition(this.getCenter()); 
});

您可以查看 了解更多信息。

虽然之前的答案是正确的并且可以解决问题,但问题仍然存在,因为 google 地图标记(有时移动得很快)不一定会到达地图的中心。

在进一步研究中,我发现实现此用例的更好解决方案是在 div 的中心保留一个单独的标记,并使用 map.getCenter() 来获取需要时的位置。

这样,唯一要添加的事件侦听器将是 dragend。

google.maps.event.addListener(map, 'dragend', (function () {
        var l = map.getCenter();
        //marker.setPosition(l);
        console.log("get center", l);
        this.updatePosition(l.lat(), l.lng());
      }).bind(this));
    }

#map {
  height: 60%;
  position: relative;
}

#map:after {
  width: 44px;
  height: 50px;
  display: block;
  content: " ";
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -40px 0 0 -11px;
  background: url("../../assets/icon/pin.png");
  background-size: 44px 50px;   

}

Pro tip: You can also use a gif instead of png. Makes the map come alive.