Submitted by Blaine on Sat, 05/14/2016 - 19:54
For the purposes of this blog, we are going to assume you are using a PHP chat bot of some sort. We make this assumption only because this is what we are using. If you are using a different programming language, please feel free to adapt the concept to your purposes. First off, when a user sends data to the chat bot containing a location from Facebook, you will receive JSON data. In order for the user to send location data, they have to click on that cool little pin (you know, the drop pin icon). The data will look a lot similar to the following when it hits your webhook:
With this data, we can then grab the longitude and latitude of the current user by grabbing the data from the returned JSON. For example, to get our longitude and latitude from this returned data, we can do something like this:
string(24) "What Sweet Hell is This?"
So now that we have latitude and longitude data, wouldn’t it be nice to get a bit more accurate with an address, or a city and state, or anything besides numbers? Well, we can, using Google Maps API.
//Read Input from Facebook
$input = json_decode(file_get_contents('php://input'), true);
//If input contains coordinates data, do something with it
//The name of the location sent
$userLocationTitle = $input['entry']['messaging']['message']['attachments']['title'];
//The Latitude of the location sent
$userLat = $input['entry']['messaging']['message']['attachments']['payload']['coordinates']['lat'];
//The Longitude of the location sent
$userLong = $input['entry']['messaging']['message']['attachments']['payload']['coordinates']['long'];
Then to get the name of the city for example, we can do the following:
$url = 'https://maps.googleapis.com/maps/api/geocode/json?&latlng=' . $userLat . ',' . $userLong;
$content = file_get_contents($url);
$json = json_decode($content, true);
Hope this is helpful when trying to get your location information from the user in Facebook Messenger. The last thing you want to do is have the user leave the experience just to provide a location. The address information is relatively accurate, and might fall apart in a big city only because of street numbers not being 100% accurate; but this is a great starting point to getting your location information from your users. So next time you need location data, make sure to ask them to hit the location button then press send; presto, you have location data!
$userCity = $json['results']['address_components']['long_name'];
To get a complete list of address components returned, try this:
The statements of the author of this blog are the opinion of the author, and do not necessarily reflect the views or opinions of Binary Computer Solutions, Inc