Jump to content

Reading output


TapeGun007
Go to solution Solved by TapeGun007,

Recommended Posts

I'm trying to create a page where if a person inputs a zip code, I can return the County, City, and State.

 

After reading about the Google API, it seems you need to register an API key and they can force a quota of some sort.  Plus they use a lot of JSON and I simple don't understand what their code is doing.

 

One way around trying to learn JSON, the Google API, registering a key and worrying about a quota, is using a form that collects the zip code and then making a call that will return a value.

 

For example, let's say I enter the zip code "91920" into the form.  I can URL encode that into the following link:

http://maps.googleapis.com/maps/api/geocode/json?address=91902&sensor=true

 

This link will send back all the information I am looking for, what I want to do is pull the information from that link/page.  I'm not sure how to accomplish this task and cannot seem to google the right question.

 

Also, let me know if you think there is a much better way to go about this process.

Link to comment
Share on other sites

this should do it

$url = 'http://maps.googleapis.com/maps/api/geocode/json?address=91902&sensor=true';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);

$data = json_decode($output,1);

echo $data['results'][0]['formatted_address'];  // Bonita, CA 91902, USA

  • Like 1
Link to comment
Share on other sites

@ginerjm, yes but that doesn't contain the county.

 

@Barand, this is my fault, because I didn't explain the results I was looking for.  In the above example is there a way to separate out the following:

 

$county = San Diego County

$city = Bonita

$state = CA

$zip = 91920

 

I will research what you just gave me, but yes that works perfectly.

Link to comment
Share on other sites

Hmmm....

 

Barand gave you back the same url that you referenced which you said you were happy with except for the part concerning retrieving the data into your script. Now you say it doesn't give you what you need. Is it simply a matter of culling a different field from the decoded data? Do a var_dump on the data and see what it contains and use it.

Link to comment
Share on other sites

I was excited to see that he could extract the city, state, and country from just a zip code so easily.

 

However, I need to separate the variables as I noted above and also need to extract the county.  I've read so many examples online, some of which are incomplete (never answered).

 

For example, I tried this to see if I could just extract the city name:

 

$request = file_get_contents ('http://maps.googleapis.com/maps/api/geocode/json?address=95117&sensor=true');
$data = json_decode( $request, true );
 
 
foreach ( $data['results'][0]['locality'] as $value ) {
    echo $value['short_name'] . '<br />';  // no value is echo'd
}

 

It does not work, so there is something I'm not understanding.

 

However this does work:

 

$request = file_get_contents ('https://maps.googleapis.com/maps/api/geocode/json?address=meerpaal%208d%20oosterhout&sensor=true');
$data = json_decode( $request, true );


foreach ( $data['results'][0]['geometry'] as $value ) {
echo $value['lat'] . '<br />';
echo $value['lng'] . '<br />'; // This will show me the longitude and latitude
}
Link to comment
Share on other sites

  • Solution

Finally.  I just kept googling different information and with both of your help, I was able to find the answer I was looking for.  I wasn't realizing that it was a multi-dimensional array.  I keep looking at the Google output, looked at the json_decode and realized that was the key to my success.  Now this may not be the BEST way to accomplish this, but it serves the purpose none the less.

 

 

$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=95117&sensor=true');
 
$output= json_decode($geocode);
 
for($j=0;$j<count($output->results[0]->address_components);$j++){
    echo '<b>'.$output->results[0]->address_components[$j]->types[0].': </b>  '.$output->results[0]->address_components[$j]->short_name.'<br/>';
    $type = $output->results[0]->address_components[$j]->types[0];
    
    switch ($type){
        case "sublocality_level_1": // Sub Locality (for foreign address')
            $ForeignAddress = $output->results[0]->address_components[$j]->short_name;
        case "locality": // Name of City
            $City = $output->results[0]->address_components[$j]->short_name;
        case "administrative_area_level_2": // County or equivalent
            $County = $output->results[0]->address_components[$j]->short_name;
        case "administrative_area_level_1": // State / Province
            $State = $output->results[0]->address_components[$j]->short_name;
        case "country": // Country
            $Country = $output->results[0]->address_components[$j]->short_name;
    }
}
echo "$City, $State, $County, $Country";

 

This also works if you have a longitude/latitude or if they are in a foreign country, you may need to store additional address information like this one:

 

 

$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=48.283273,14.295041&sensor=false');
Link to comment
Share on other sites

There is an old compsci saying: "Garbage in garbage out".

 

In order to determine what data you have to work with, you need to to dump out the data structure in some human understandable way so that you can check your assumptions.

 

There are several tools for this in php: var_dump and print_r for example.

 

I also think that given a small amount of effort, you could probably learn to understand JSON format, which is fairly easy to understand if you invest maybe 20 minutes studying it online and looking at some examples.

 

Here is the raw JSON output from your example:

 

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "95117",
               "short_name" : "95117",
               "types" : [ "postal_code" ]
            },
            {
               "long_name" : "San Jose",
               "short_name" : "San Jose",
               "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" ]
            }
         ],
         "formatted_address" : "San Jose, CA 95117, USA",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 37.3299101,
                  "lng" : -121.9499179
               },
               "southwest" : {
                  "lat" : 37.2943199,
                  "lng" : -121.9817339
               }
            },
            "location" : {
               "lat" : 37.3120731,
               "lng" : -121.9643745
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 37.3299101,
                  "lng" : -121.9499179
               },
               "southwest" : {
                  "lat" : 37.2943199,
                  "lng" : -121.9817339
               }
            }
         },
         "place_id" : "ChIJ4YcqPMHKj4AR_oe_L8U_ojs",
         "types" : [ "postal_code" ]
      }
   ],
   "status" : "OK"
}
In the code you provided, which simply converts the JSON to a php array, once you understand JSON a bit you can figure out what the array structure is going to look like.

 

It appears that determine the city data isn't as simple as finding a fixed key, because the structure contains an array named 'address_components' with a number of generic sub objects. You have to actually look for the 'locality' key in the list of types for that embedded object:

 

            {
               "long_name" : "San Jose",
               "short_name" : "San Jose",
               "types" : [ "locality", "political" ]
            },
So for example, I can see that something like this would seem to allow you to determine the city component:

 

$city = array();
foreach ($data['results'][0]['address_components'] as $addrObj) {
    foreach($addrObj['types'] as $type) {
         if ('locality' == $type) {
             $city['short_name'] = $addrObj['short_name'];
             $city['long_name'] = $addObj['long_name'];
         } 
    }
}
Of course, I'd highly recommend using var_dump($data) to debug these assumptions.
Link to comment
Share on other sites

gizmola,

 

I'm no expert php coder per se.  I've been asked to do a fairly complex job at work with my little bit of knowledge.  I've written some decent code, but never used json or var_dump.  I've written pretty simple stuff like writing to mySQL databases.  Now I've had to completely re-learn that using mySQLi.

 

At the time of this post, I didn't realize that there wasn't much to json.  Most of my post was just reaching out because I had no idea where to even start.  All of the code that I had looked at wasn't working.  Barand got me on the right track of research as I never mind learning or taking the time to learn on my own.  As I read though his curl example it led me to read up on the json_decode which in turn helped me to understand what json was.  I had the raw json up at one point and viewing it helped me to understand Barands code better as well as other examples.

 

Most of what I'm trying to understand is not just what code works, but how it works.  Sometimes the lack of explanations leaves me hanging a bit.  Thank you for your input as well.

 

I'll have to learn how to use the var_dump better to understand how best to use that tool to help debug my code.  

Link to comment
Share on other sites

Personally I prefer to use print_r() and only use var_dump() when I need to check type and size and see if there is any hidden whitespace or non-printable characters. When using either, use between <pre>..</pre> tags. It makes it much more readable.

 

eg

$output= json_decode($geocode);
echo '<pre>', print_r($output), '</pre>';
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.