angular - 如何将 map 设置为以标记为中心? - Angular 谷歌地图

标签 angular geolocation marker angular-google-maps

地理编码后,我无法将我的 Google map 置于标记上。

我有两个标记:初始标记(一个居中的,不改变),另一个根据地理编码改变,地理编码后,每次都会居中。

我的代码:客服

zoom = 10;

addressData: FormGroup;
submitted = false;
success = false;

lat: number;
lng: number;

userLat: number;
userLng: number;

currentCenter = { lat: null, lng: null };

private geoCoder: google.maps.Geocoder;

@ViewChild('googleMap') googleMap: AgmMap;

constructor(private maps: MapsAPILoader, private bulider: FormBuilder) { }

ngOnInit() {
    this.addressData = this.bulider.group({
        address: ["", Validators.required],
    });

    this.maps.load().then(() => {
        this.geoCoder = new google.maps.Geocoder();
    });
}

getAddress() {

    this.submitted = true;

    if (this.addressData.invalid) {
        return;
    }

    this.success = true;

    this.googleMap.mapReady.subscribe(map => {

        // Need to use two parameters in order to use Geocoder
        this.geoCoder.geocode(this.addressData.controls['address'].value, (results, status) => {
        if (status === google.maps.GeocoderStatus.OK) {
            this.userLat = results[0].geometry.location.lat();
            this.userLng = results[0].geometry.location.lng();
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }

    }).then(place => {
        this.currentCenter = { lat: place.geometry.location.lat(), lng: place.geometry.location.lng() };
    }).catch(err => {
        console.log("Error: " + err);
    });

    this.submitted = false;
}

HTML
<!-- Google maps, the starting latitude & longitude -->
<agm-map [latitude]="currentCenter.lat" [longitude]="currentCenter.lng" [zoom]="zoom" [mapTypeControl]='true'
#googleMap>
    <!-- Static marker -->
    <agm-marker [latitude]="defaultCenter.lat" [longitude]="defaultCenter.lng"></agm-marker>

    <!-- User geolocation marker, changes -->
    <agm-marker [latitude]="currentCenter.userLat" [longitude]="currentCenter.userLng"></agm-marker>
</agm-map>

预计 :

地理编码后, map 每次都应以给定地址的标记为中心。

实际 :

地理编码器会找到地址,但不会根据地址将 map 放在放置的标记上。

更新

我不能使用 Vadim 的代码,因为编译器告诉我 Geocode 需要两个参数。 ,但 Vadim 的代码只有一个。我无法使用此代码。另外,如果我添加第二个参数,它会说 then不存在。
this.googleMap.mapReady.subscribe(map => {
    // This line needs two parameters not one      

    this.geoCoder.geocode(this.addressData.controls['address'].value)
    .then(place => {
        this.currentCenter = { lat: place.geometry.location.lat(), lng: place.geometry.location.lng() };
    }).catch(err => {
        console.log("Error: " + err);
    });
});

最佳答案

无需借助 Google Maps API 或调用 Map 组件 triggerResize方法,要更新 map 中心,可以考虑以下方法:

a) 加载 map 后将 map 中心设置为默认值

<agm-map
  [latitude]="currentCenter.lat"
  [longitude]="currentCenter.lng"
  [zoom]="zoom"
  [mapTypeControl]="true"
>
  <!-- Static marker -->
  <agm-marker
    [latitude]="defaultCenter.lat"
    [longitude]="defaultCenter.lng"
  ></agm-marker>

  <!-- User geolocation marker, changes -->
  <agm-marker
    [latitude]="currentCenter.lat"
    [longitude]="currentCenter.lng"
  ></agm-marker>
</agm-map>

为此,引入了两个属性:
  • currentCenter - 当前 map 中心
  • defaultCenter - 默认(原始) map 中心

  • b) 一旦地址被解析,像这样更新 map 中心:
    ngOnInit() {
        this.agmMap.mapReady.subscribe(map => {
          this.geocode("New York, USA").then(place => {
            this.currentCenter = { lat: place.geometry.location.lat(), lng: place.geometry.location.lng()};
          })
          .catch(err => {
            console.log(err);
          });
        });
     }
    

    示例
    declare var google: any;
    
    import { Component, ViewChild, OnInit} from "@angular/core";
    import { AgmMap } from "@agm/core";
    
    @Component({
      selector: "app-map",
      templateUrl: "./app.component.html",
      styleUrls: ["./app.component.css"]
    })
    export class AppComponent implements OnInit {
      constructor() {}
    
      defaultCenter = {lat: 55.5815245, lng: 36.8251383};
      currentCenter = Object.assign({}, this.defaultCenter);
      zoom = 3;
    
      @ViewChild(AgmMap) agmMap;
    
      ngOnInit() {
        this.agmMap.mapReady.subscribe(map => {
          this.geocode("New York, USA").then(place => {
            this.currentCenter = { lat: place.geometry.location.lat(), lng: place.geometry.location.lng()};
          })
          .catch(err => {
            console.log(err);
          });
        });
      }
    
      geocode(address: string): Promise<any> {
        const geocoder = new google.maps.Geocoder();
        return new Promise((resolve, reject) => {
          geocoder.geocode(
            {
              address: address
            },
            (results, status) => {
              if (status === google.maps.GeocoderStatus.OK) {
                resolve(results[0]);
              } else {
                reject(new Error(status));
              }
            }
          );
        });
      }
    }
    

    更新

    从输入元素获取地址:
    <input [(ngModel)]="addressText">
    <button (click)="findPlace()">Find a place</button>
    
    
    findPlace() {
        this.geocode(this.addressText).then(place => {
          this.currentCenter = { lat: place.geometry.location.lat(), lng: place.geometry.location.lng()};
        })
        .catch(err => {
          console.log(err);
        });
    }
    

    关于angular - 如何将 map 设置为以标记为中心? - Angular 谷歌地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56891073/

    相关文章:

    python - 为什么这个 SPARQL 查询缺少这么多结果?

    javascript - 如何获得用户当前位置的最大准确性

    javascript - 如何从 google maps api 中删除 RichMarker 阴影类?

    传单 : How to have new marker in first click then update the latlng of marker in second click

    angular - 将自定义指令动态添加到组件中的 ng-template

    android - PhoneGap - Android 上的 Cordova 2.1 地理定位不一致

    javascript - 覆盖 Angular2/4 中的组件模板?

    javascript - 如何在Mapbox中添加点?

    css - 通过 Angular 获取应用于元素的类属性

    javascript - 使用 ng-content 选择基类