【问题标题】:Adding Google map API within the Angular 2 form在 Angular 2 表单中添加 Google 地图 API
【发布时间】:2018-07-10 13:25:28
【问题描述】:

我需要从 Google 地图中获取地址,并希望将该地址解析为表单。

这是我如何将地图集成到 Angular 2 中的代码

register.component.ts

ngAfterViewInit() {
    var myLatlng = new google.maps.LatLng(-25.363882, 131.044922);
    var mapOptions = {
      zoom: 4,
      center: myLatlng
    }
    var map = new google.maps.Map(document.getElementById("googleMap"), mapOptions);

    // To add the marker to the map, use the 'map' property
    var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: "Hello World!"
    });
  }

register.component.html

<div id="googleMap" style="width:500px;height:380px;"></div>

index.html

<script src="http://maps.googleapis.com/maps/api/js?key=[api_key]"></script>

这里我只是整合了地图而已。

我希望地图具有以下属性:如果我拖动标记,它需要获取并解析我离开标记的位置的 json 地址

address={
    country:"",
    state:"",
    pincode:"",
    city:"",
    street:""
    }

我想要这样的最终地址。 谁能帮我实现这个目标?

【问题讨论】:

    标签: angular forms google-maps angular2-forms


    【解决方案1】:

    您的代码中缺少的第一件事是我拖动标记的事件侦听器。

    在创建标记时首先在标题后添加:

    position: myLatlng,
    map: map,
    title: "Hello World!",
    draggable: true
    

    然后是监听器:

    google.maps.event.addListener(marker, 'dragend', function(event) {
    
    // Here goes the code thats going to execute after you finish dragging the marker
    
    });
    

    现在您在完成拖动标记后要做的是使用标记的 lat 和 lng 进行反向地理编码,您需要通过响应来获取所需的信息。

    关于反向地理编码: https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding

    关于如何实现geocode API: https://developers.google.com/maps/documentation/geocoding/intro

    关于反向地理编码响应: https://developers.google.com/maps/documentation/geocoding/intro#reverse-example

    正如您在响应中看到的,您有“类型”,告诉您地址的类型,如街道或邮政编码,在“long_name”中,该类型的实际值。

    不是那么难,只需要做一点功课。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-14
      • 1970-01-01
      • 2014-01-02
      • 2018-07-22
      • 2015-09-19
      • 1970-01-01
      相关资源
      最近更新 更多