使用谷歌地图自动完成使用angularjs获取经度和经度json格式

时间:2016-10-26 11:20:49

标签: angularjs json google-maps google-maps-api-3 spring-boot

如何使用使用angularjs自动完成谷歌地图获取纬度和经度json格式。

2 个答案:

答案 0 :(得分:0)

在HTML文件中添加以下脚本和函数,或者您可以将函数移动到JS本身,这将是一种更简洁的方法。     

<script type="text/javascript">
    function init() {
    var places = new google.maps.places.Autocomplete(document.getElementById('input'));

    google.maps.event.addListener(places, 'place_changed', function() {
        var place = places.getPlace();
        var address = place.formatted_address;
        var latitude = place.geometry.location.lat();
        var longitude = place.geometry.location.lng();
        var mesg = "Address: " + address;
        mesg += "\nLatitude: " + latitude;
        mesg += "\nLongitude: " + longitude;
        alert(mesg); //will alert after selection...
    });
    }
    google.maps.event.addDomListener(window, 'load', init); 
</script>

在您的HTML中

<input type="text" id="input" ng-model="result"  data-tap-disabled="true" placeholder="Enter an location" data-search="input">

答案 1 :(得分:0)

我找到了一些解决方案!

app.directive('googleplace', [function (){
    return {
      restrict: 'EA',
      require: 'ngModel',
      replace: true,
      scope: {
        ngModel: '=',
        place: '=?'

      },
      link: function(scope, element, attrs, model){
        google.maps.places.autocomplete(element[0], options);
        var options = {
          types: ['(geocode)'],
          componentRestrictions: {}
        };

        scope.googleplace = new google.maps.places.Autocomplete(element[0], options);

        goole.maps.event.addListner(scope.googleplace, 'place_changed', function(){
          var geoComponents = scope.googleplace.getPlace();
          var latitude = geoComponents.geometry.location.lat();
          var longitude = geoComponents.geometry.location.lng();

          var addressComponents = geoComponents.address_components;

          addressComponents = addressComponents.filter(function(component){
            switch (component.types[0]) {
              case "locality": // cities
                return true;
              case "administrative_area_level1": //state
                return true;
              case "postal_code": // postal code
                return true;
              case "country": // country
                return true;
              default:
                return false;

            }
          }).map(function(obj) {
              return obj.long_name;
          });

          addressComponents.push(latitude, longitude);

          scope.$apply(function(){
            scope.details = addressComponents; //array containing each location component
            mode.$setViewValue(element.val());
          });

          scope.$on('$destroy', funcion(){
            google.maps.event.clearInstanceListerners(element[0]);
          });

        });
      }
    };
  }]);