【问题标题】:Javascript Angular Google Map Autocomplete Api not workingJavascript Angular Google Map Autocomplete Api 不起作用
【发布时间】:2016-12-05 03:34:06
【问题描述】:

我正在尝试使用以下代码以角度设置 google map api: HTML:

<div ng-value="initMap()"> 
          <div>
          <input id="pac-input" type="text"
                  value="{{event_foundaddress}}"  ng-model="event_foundaddress"/> <!-- placeholder breaks EVERYTHING!!!! No placeholder!!!-->
          </div>

          <div  id="map" style="width: 300px; height: 400px" > </div>

          <div > Found address: {{event_foundaddress}} </div>
       </div>

JS/角度

$scope.initMap = function() {
    var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: $scope.lat, lng: $scope.long},//london coords
    zoom: 13
  });
  $scope.foundaddress = $localStorage.event.address
  var input = /** @type {!HTMLInputElement} */
      (document.getElementById('pac-input'));
     //$scope.event_foundaddress
  //alert('in:'+input)
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
  //var types = document.getElementById('type-selector');
  //map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
  //alert(input)
  var autocomplete = new google.maps.places.Autocomplete(input,{types: ['geocode']});
  autocomplete.bindTo('bounds', map);


  var infowindow = new google.maps.InfoWindow();
  var marker = new google.maps.Marker({
    map: map,
    anchorPoint: new google.maps.Point(0, -29)
  });


  autocomplete.addListener('place_changed', function() {...


  }

我收到一个错误 InvalidValueError: not an instance of HTMLInputElement from the var autocomplete = new google.maps.places.Autocomplete(input,{types: ['geocode']});。显然输入不是 HTMLInputElement。你知道如何从 dom 中通过 Angular 传递 HTMLInputElement 吗?

编辑: 放置一个 alert('input') 表明输入变量始终为空......不知道为什么?

【问题讨论】:

    标签: javascript html angularjs google-maps


    【解决方案1】:

    我遇到了同样的问题,您必须在输入元素的ng-focus 上调用initMap()。然后它将起作用。

    但是即使在更新我的代码之后,模型也没有更新。然后我搬到了 angular-google-places-autocomplete 库。

    那个图书馆太棒了。查看https://github.com/kuhnza/angular-google-places-autocomplete

    编辑:答案已更新 你只需要写如下,一旦你选择了foundaddress的位置,就会有Google place对象,你必须从中提取formatted_address。

    <input ng-model="foundaddress" type="text" id="pac-input" g-places-autocomplete></input>
    

    【讨论】:

    • 如果我把 。代码甚至没有加载地图
    • 使用这个,var map = new google.maps.Map(document.getElementById('pac-input') 你传递了正确的 id
    • 我不认为名称是问题:'map' id 是显示地图的地方,'pac-input' 是应该执行自动完成的地方
    • 我也尝试了 angular-google-places-autocomplete 库,但在 var autocomplete = new google.maps.places.Autocomplete(input,{types: ['geocode']});
    • 我已经更新了我的答案,请查看。如果您使用 angular-google-places-autocomplete 库,则不需要使用 initMap()
    猜你喜欢
    • 2014-10-30
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多