asasa178
asasa178

Reputation: 221

Javascript Angular Google Map Autocomplete Api not working

I'm trying to se the google map api in angular with the following code: 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/angular

$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() {...


  }

I got an error InvalidValueError: not an instance of HTMLInputElement from the var autocomplete = new google.maps.places.Autocomplete(input,{types: ['geocode']});. Apparently input is not a HTMLInputElement. Do you know how to pass through a HTMLInputElement from the dom in angular?

EDIT: putting an alert('input') reveals that the input variable is always null... not sure why?

Upvotes: 0

Views: 1234

Answers (1)

Naveen
Naveen

Reputation: 830

I had the same issue, you have to call initMap() on ng-focus of input element. Then it will work.

But the problem even after updating my code, the model wasnt updated. Then I moved to angular-google-places-autocomplete library.

And that library is awesome. Check out https://github.com/kuhnza/angular-google-places-autocomplete

Edit: Answer Updated You just have to write as below, and once you select the location foundaddress will have Google place object, from which you have to extract formatted_address.

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

Upvotes: 1

Related Questions