Angular 将标记针保持在中心,我会拖动地图吗

Angular 将标记针保持在中心,我会拖动地图吗,angular,google-maps-api-3,ionic4,Angular,Google Maps Api 3,Ionic4,我正在构建一个使用IONIC框架使用GoogleMapsAPI的用例 在页面中显示地图后,标记pin位于位置(lat、lng),我需要允许用户拖动地图,保持pin固定,以便他们可以精确定位自己的地址,在拖动停止时,我需要获取点的lat、lang和获取点的地址,并显示在UI中。我怎样才能做到这一点 下面是我用来显示带有PIN的地图的代码 ngAfterContentInit(): void { this.map = new google.maps.Map( this.mapNativeE

我正在构建一个使用IONIC框架使用GoogleMapsAPI的用例

在页面中显示地图后,标记pin位于位置(lat、lng),我需要允许用户拖动地图,保持pin固定,以便他们可以精确定位自己的地址,在拖动停止时,我需要获取点的lat、lang和获取点的地址,并显示在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()); 
});

您可以查看更多信息。

尽管前面的答案是正确的,并且可以完成任务,但问题仍然存在,因为谷歌地图标记(在快速移动时)不一定会出现在地图的中心

在进一步研究中,我发现实现此用例的更好解决方案是在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;   
}

专业提示:你也可以用gif代替png。让地图来 活着