简体   繁体   中英

Ionic / Angular JS - Get specific values from Reverse Geolocation

I am building an App using Ionic / Angular JS. In a specific tab, the app has the ability to fill some form fields automatically like Street Name, Street Number, etc. My problem is that, in some situations the Street Number for example is not available and data[0].address_components[0].long_name fills the Street Name instead.

Here is the code that I use:

.controller('PetitionsCtrl', function($scope, $cordovaGeolocation, $cordovaCamera, $log, $ionicLoading, $http, $timeout, $compile, Upload) {


  $scope.getLocation = function() {
    $ionicLoading.show({
      templateUrl: 'loading.html',
      hideOnStateChange: true
    });
      var posOptions = {timeout: 15000, enableHighAccuracy: true};
      $cordovaGeolocation
      .getCurrentPosition(posOptions)
      .then(function (position) {
        $scope.lat = position.coords.latitude;
        $scope.lng = position.coords.longitude;
        $scope.pLat = {value: $scope.lat};
        $scope.pLng = {value: $scope.lng};

        var geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng($scope.lat, $scope.lng);
        var request = {
          latLng: latlng
        };

        geocoder.geocode(request, function(data, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (data[0] != null) {
              $scope.$apply(function () {
                $scope.pStreet = {value: data[0].address_components[1].long_name};
                $scope.pNumber = {value: data[0].address_components[0].long_name};
                $scope.pCity = {value: data[0].address_components[2].long_name};
                $scope.pAddress = {value: data[0].formatted_address};
                setTimeout(function () {
                  $ionicLoading.hide();
                }, 500);
              });
            } else {
              $log.log("Adresa indisponibila");
              setTimeout(function () {
                $ionicLoading.hide();
              }, 500);
            }
          }
        })
      });
    };
})

Here is an example response from Google:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "1600",
               "short_name" : "1600",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Amphitheatre Pkwy",
               "short_name" : "Amphitheatre Pkwy",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Mountain View",
               "short_name" : "Mountain View",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Santa Clara County",
               "short_name" : "Santa Clara County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "California",
               "short_name" : "CA",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "94043",
               "short_name" : "94043",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
         "geometry" : {
            "location" : {
               "lat" : 37.4224764,
               "lng" : -122.0842499
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 37.4238253802915,
                  "lng" : -122.0829009197085
               },
               "southwest" : {
                  "lat" : 37.4211274197085,
                  "lng" : -122.0855988802915
               }
            }
         },
         "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"
}

How can I alter my code so it checks the "types" value before reading a value and leaves it empty if not available. To be more speicifc, instead of using data[0].address_components[0].long_name to get the street number, I would like to get if "types" vale is "street_number" .

What I have understood is that if the types value is equal to street_number you want to get the value otherwise you want to put empty as a value ''

geocoder.geocode(request, function(data, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (data[0] != null) {
              $scope.$apply(function () {
                $scope.pStreet = {value: data[0].address_components[1].long_name};
                $scope.pNumber = {value: data[0].address_components[0].types[0] === 'street_number' ? data[0].address_components[0].long_name : ''};
                $scope.pCity = {value: data[0].address_components[2].long_name};
                $scope.pAddress = {value: data[0].formatted_address};
                setTimeout(function () {
                  $ionicLoading.hide();
                }, 500);
              });
            } else {
              $log.log("Adresa indisponibila");
              setTimeout(function () {
                $ionicLoading.hide();
              }, 500);
            }
          }
        })

You have to loop over result set to find a match like:

Angular.forEach(data[0].address_components, function(val, index){ 
   if (val.type[0]=='street_number') {
      $scope.pNumber = {value: val.long_name};
   }
});

You can use this code to find any other value like city or country etc.

Ryad.iv answer is just checking the first string in the array. For this to work properly you have to check all the elements of the array.

geocoder.geocode(request, function(data, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (data[0] != null) {
              $scope.$apply(function () {
                $scope.pStreet = {value: data[0].address_components[1].long_name};
                $scope.pNumber = {value: data[0].address_components[0].types.indexOf('street_number') !== -1 ? data[0].address_components[0].long_name : ''};
                $scope.pCity = {value: data[0].address_components[2].long_name};
                $scope.pAddress = {value: data[0].formatted_address};
                setTimeout(function () {
                  $ionicLoading.hide();
                }, 500);
              });
            } else {
              $log.log("Adresa indisponibila");
              setTimeout(function () {
                $ionicLoading.hide();
              }, 500);
            }
          }
        })

That's the good way of checking this. With the other answer, if street_name is the second position of the array you will not be inserting it correctly.

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM