Yahoo Maps-based Geocoding
I recently had to create online maps for an art gallery, specifically for their exhibits. So I decided to use the Yahoo API to grab the coordinates based upon the data that was being sent to the model and save this to the database. Here's how I did it.
First, the model has to be aware of the Yahoo AppID. I set this as a variable within the model itself, but you can set it in the url.
1 2 3 4 5 6 7 | |
Next we should probably actually get the Latitude and Longitude for the data. I am assuming you have the correct fields defined in your exhibits table. The CREATE TABLE query is shown below
1 2 3 4 5 6 7 8 9 10 | |
Now that you have the proper fields, we'll REALLY get the Latitude and Longitude. Below is the entire Model class relating to Exhibits:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
I have allowed you to use either cURL or fopen. For cURL, you need to have that installed on your server, and for fopen, you need to have allow_url_fopen set to true in php.ini. Just giving options in case you can't do one or the other :)
You'll notice that when I get the State for this location, I initialize the model via ClassRegistry. Just out of habit. I also don't have a relationship to the State in my model, which is why I did this. Read about Containable (and BindModel for extra points!) for more information. The code for that call in the State model is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
So lets review:
- I set my AppID somehow
- Made sure my model contained the proper fields
- Added some code to the beforeValidate
- Updated two fields (latitude and longitude) in my model
- Made getting the State (depending upon state_id) a bit easier
You can now use the Latitude and Longitude in the views just as any other model data.
I realize that you might be thinking "This should be a behavior or something, I'll end up replicating this several times!" Well good. You make the behavior and I'll take credit! In all seriousness though, there is already a Geocode Model on the bakery that should be made into a behavior. This was just a quick fix before I converted it into a Behavior for my own usage :)
Discussion