Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Feb 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question how to splite results from object returned from google maps reverse geolocation

    I'm trying to split up or filter results returned from google maps reversegeoloaction api.

    I have a working example here:

    http://cdpn.io/hHFts

    The problem is, the reversegeolocation object that returns is a complex object literal with a whole bunch of values.. Way too many basically.

    In the UK we only need a 7 character postcode, and my input field is stuffed with way too many characters.

    Is there any way I can split or filter the result object so I can only grab the first results, whihc would hopefully give me the first 7 chracters I need.. (8 characters if you count a space).

    I've tried limiting the input field with html max characters (sorry, its dirty I know but it didn't work..

    I've been scratching my head over this for a few days now. Any help would be awesome.

    Thanks

    Here's the code too:

    Code:
        window.onload = function(){
    
    //var long = '50.**************', lat = '0.**************'
        var Lat='';
        var Long='';
        var coordsObj = {coords:{latitude:Lat, longitude:Long}};
    
        if (navigator.geolocation) {
          var timeoutVal = 10 * 1000 * 1000;
          navigator.geolocation.getCurrentPosition(
            displayPosition, 
            displayError,
            { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
          );
        }
        else {
          alert("Geolocation is not supported by this browser");
        }
    
        function displayPosition(position) {
            //console.log(position, position.coords)
            //console.log("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
            var Lat = position.coords.latitude;
            var Long = position.coords.longitude;
            reverseGeoLookup(Lat, Long);
            //alert(Lat);
            //alert(Long);
        }           
    
        function displayError(error) {
          var errors = { 
            1: 'Permission denied',
            2: 'Position unavailable',
            3: 'Request timeout'
          };
          alert("Error: " + errors[error.code]);
        }
    
        function reverseGeoLookup(lat, lon) {
          var req = new XMLHttpRequest();
          //console.log("requesting: ", "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true")
          req.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true", true);
          req.onreadystatechange = function() {
              if(req.readyState == 4) {
                  var result = JSON.parse(req.response).results
                  for(var i = 0, length = result.length; i < length; i++) {
                      for(var j = 0; j < result[i].address_components.length; j++) {
                          var component = result[i].address_components[j];
    
    //This bit here grabs the postal_code bits, and the tilde negative operator returns the     postcode values rather than the address names.. not sure how.
    // I need some sort of filter or loop here to grab the first or just one of these postal code elements, at the moment I get too many...
                        if(~component.types.indexOf("postal_code")) {
                            var outPut = document.getElementById('addressInput');
                            outPut.value += component.short_name;
                          }
                      }
                  }
              }
          }
          req.send();
        }
    
    var latlng = displayPosition(coordsObj);
    reverseGeoLookup.apply(this, latlng);
    
    };

  • #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,931
    Thanks
    56
    Thanked 552 Times in 549 Posts
    you are looping over the entire results returned with this line:
    Code:
    for(var i = 0, length = result.length; i < length; i++) {
    and then looping over every address component in those results with this line:
    Code:
    var component = result[i].address_components[j];
    and then, for each hit you are adding it to the input box with this line:
    Code:
    outPut.value += component.short_name;
    the quick answer would be to remove the concatenation:
    Code:
    outPut.value = component.short_name;
    so that the value gets overwritten every time the loop goes around and you only end up with the last one. If you wanted to get more specific, you should have a look at the structure of the object returned, ie:
    http://maps.googleapis.com/maps/api/....9&sensor=true

    and decide how to cherry pick the result you want

  • #3
    New to the CF scene
    Join Date
    Feb 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks for the spot xelawho!
    Its working much better now.. Although the last result isn't quite the one I need.

    You mentioned:
    and decide how to cherry pick the result you want
    Is there a way I can get just the first result?

    (I know the json object won't always be in the same order, but I think in this case the first result will work most of the time..)

    Failing that, how would I get just the result I want when they all have the same names??

    Here's a sample object i get back from central London:

    Code:
    {
       "results" : [
          {
             "address_components" : [
                {
                   "long_name" : "138",
                   "short_name" : "138",
                   "types" : [ "street_number" ]
                },
                {
                   "long_name" : "Shaftesbury Avenue",
                   "short_name" : "Shaftesbury Ave",
                   "types" : [ "route" ]
                },
                {
                   "long_name" : "London",
                   "short_name" : "London",
                   "types" : [ "locality", "political" ]
                },
                {
                   "long_name" : "Greater London",
                   "short_name" : "Gt Lon",
                   "types" : [ "administrative_area_level_2", "political" ]
                },
                {
                   "long_name" : "United Kingdom",
                   "short_name" : "GB",
                   "types" : [ "country", "political" ]
                },
                {
                   "long_name" : "WC2H 8HB",
    
    //   I JUST WANT TO GET THIS LITTLE CHAP BELOW:
    
                   "short_name" : "WC2H 8HB",
                   "types" : [ "postal_code" ]
                },
                {
                   "long_name" : "London",
                   "short_name" : "London",
                   "types" : [ "postal_town" ]
                }
             ],
             "formatted_address" : "138 Shaftesbury Avenue, London, Greater London WC2H 8HB, UK",
             "geometry" : {
                "location" : {
                   "lat" : 51.51303350,
                   "lng" : -0.12923720
                },
                "location_type" : "ROOFTOP",
                "viewport" : {
                   "northeast" : {
                      "lat" : 51.51438248029149,
                      "lng" : -0.1278882197084980
                   },
                   "southwest" : {
                      "lat" : 51.51168451970850,
                      "lng" : -0.1305861802915020
                   }
                }
             },
             "types" : [ "street_address" ]
          },
          {
             "address_components" : [
                {
                   "long_name" : "Soho, Cambridge Circus (WC2) (Stop D)",
                   "short_name" : "Soho, Cambridge Circus (WC2) (Stop D)",
                   "types" : [ "bus_station", "transit_station", "establishment" ]
                },
                {
                   "long_name" : "London",
                   "short_name" : "London",
                   "types" : [ "locality", "political" ]
                },
                {
                   "long_name" : "City of Westminster",
                   "short_name" : "City of Westminster",
                   "types" : [ "administrative_area_level_3", "political" ]
                },
                {
                   "long_name" : "Greater London",
                   "short_name" : "Gt Lon",
                   "types" : [ "administrative_area_level_2", "political" ]
                },
                {
                   "long_name" : "United Kingdom",
                   "short_name" : "GB",
                   "types" : [ "country", "political" ]
                },
                {
                   "long_name" : "WC2H",
    
    // NOT THIS ONE
    
                   "short_name" : "WC2H",
                   "types" : [ "postal_code_prefix", "postal_code" ]
                }
             ],
             "formatted_address" : "Soho, Cambridge Circus (WC2) (Stop D), City of Westminster, London WC2H, UK",
             "geometry" : {
                "location" : {
                   "lat" : 51.513420,
                   "lng" : -0.12920
                },
                "location_type" : "APPROXIMATE",
                "viewport" : {
                   "northeast" : {
                      "lat" : 51.51476898029149,
                      "lng" : -0.1278510197084980
                   },
                   "southwest" : {
                      "lat" : 51.51207101970849,
                      "lng" : -0.1305489802915020
                   }
                }
             },
             "types" : [ "bus_station", "transit_station", "establishment" ]
          },

  • #4
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,931
    Thanks
    56
    Thanked 552 Times in 549 Posts
    if you want the first result, it would make sense to restrain the results to results[0]:

    Code:
    <html>
    <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&sensor=true"></script>
    </head>
    <body>
    <script type="text/javascript">
    var geocoder = new google.maps.Geocoder();
    var lat= 51.51303;
    var lng=-0.12924;
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
    		for (var i=0; i<results[0].address_components.length; i++){
              if (results[0].address_components[i].types=="postal_code"){
    		  alert(results[0].address_components[i].long_name);
    				}
    		  }
            }
          } else {
            alert("Geocoder failed due to: " + status);
          }
        });
    </script>
    </body>
    </html>
    it may help to understand the various detail levels returned by the geocoder:
    https://developers.google.com/maps/d...verseGeocoding

    but if you don't want the first result, which is the result you want?


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •