celsomtrindade
celsomtrindade

Reputation: 4671

Google Maps Api run getPlaces with custom string

I'm using Google Maps autocomplete feature and everything is working fine.

But I'd like to know if it's possible to run .getPlace() function from a custom string, wether it's coordinates or address. For example, instead of using an input field and click on the location to select it, I'd like to call it manually, like this:

var myAutoComplete = new google.maps.places.Autocomplete('City, Country');

And it return the same as a normal autocomplete. The reason why I want to do this, is because somethis I get users location from html5 geolocation (or other method) and I'd like to run the getPlace function with that data.

The getPlace function from google return a more complete set of data, with all the names, coordinates, pictures from that city, etc..

By the way, I'm using Google Maps with AngularJs with this module: ngMap.


Edit: Posting the code I have so far as requested on the comments.

//HTML
<input places-auto-complete on-place-changed="vm.placeChanged()" />


//Controller
function MainController(NgMap) {
    var vm = this;

     vm.placeChanged = function() {
        var param = {
            maxWidth: 1920,
            maxHeight: 1080
        };

        var autocomplete = this.getPlace();

        console.log('Result: ', autocomplete);
        console.log(autocomplete.geometry.location.lat());
        console.log(autocomplete.geometry.location.lng());
        console.log(autocomplete.photos[0].getUrl(param));
    }
}

The input automatically generate the autocomplete feature, when I select one address option, the function is called and I get all the response correctly.

What I want is to call the same function, but instead of using the autocomplete from google, I want to pass my own string and return the same data as the function.


As suggested on the comments, I tried using a custom directive to run the same autocomplete, this is my plunkr: http://plnkr.co/edit/hcRXJxB7ItN6YtISWdx3?p=preview

Upvotes: 2

Views: 1212

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59348

Autocomplete object does not support such kind of scenario, it could only be attached to the specified input text field from where the user selects the item and the correspinding place is returned.

Instead you could utilize AutocompleteService class which in my opinion suits your scenario very closely

According to official documentation AutocompleteService class

does not add any UI controls. Instead, it returns an array of prediction objects, each containing the text of the prediction, reference information, and details of how the result matches the user input. This is useful if you want more control over the user interface than is offered by the Autocomplete

The following example demonstrates how to return the details of the Place from input string entered in text box

Example

var app = angular.module('myApp', ['ngMap']);

app.controller('MyCtrl', function ($scope,NgMap) {
  var vm = this;
  vm.center = [0,0];

  vm.types = "['establishment']";

  NgMap.getMap().then(function (map) {
    vm.map = map;
  });

  vm.addressResolved = function (value) {

    $scope.$apply(function () {
      vm.address = value.address_components;
      vm.center = value.geometry.location;
    });




  }

});


app.directive('myComplete', function (NgMap) {
  return {
    restrict: 'A',
    scope: {
      map: '=',
      addressResolved: '&addressResolved'
    },
    link: function (scope, element, attrs) {
      // on blur, update the value in scope
      element.bind('blur', function (blurEvent) {

        var service = new google.maps.places.AutocompleteService();
        service.getQueryPredictions({ input: element.val() }, function (predictions, status) {
          if (status == google.maps.places.PlacesServiceStatus.OK) {

            if (predictions.length > 0) {
              element.val(predictions[0].description);


              var service = new google.maps.places.PlacesService(scope.map);
              service.getDetails({
                placeId: predictions[0].place_id
              }, function (place, status) {
                if (status === google.maps.places.PlacesServiceStatus.OK) {

                  scope.addressResolved({ place: place });
                }
              });
            }
          }
        });
      });
    }
  };

});
<script src="https://maps.google.com/maps/api/js?libraries=placeses,visualization,drawing,geometry,places"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
  <script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>

<div ng-app="myApp" ng-controller="MyCtrl as vm">
  Auto Complete Type:
  <select ng-model="vm.types">
    <option value="['geocode']">Geodode</option>
    <option value="['establishment']">Establishment</option>
    <option value="['address']">Address</option>
  </select><br/>

  
  <h3>Custom directive usage</h3>
  <input my-complete address-resolved="vm.addressResolved(place)" map="vm.map" />
  address : <pre>{{vm.address | json}}</pre>  
  <ng-map  zoom="12" center="{{vm.center}}"></ng-map>
</div>

Demo

Upvotes: 2

Related Questions