We’ve long been used to using Google’s tools and services to do a lot of things… only good things come to an end and some of these services close or become paid for.
As part of the development of my OpenAgenda plugin for WordPress, I need to find the longitude and latitude of an event address.
OpenStreetMap to the rescue
Fortunately, there are many services that can replace those of Google. Among them OpenStreetMap (OSM) for everything that revolves around maps and geolocation.
Nominatim for the conversion of address to location data.
So I discovered the Nominatim service.
That’s all very nice, but I want code!
If like me, you need to retrieve the latitude and longitude of a geographic point in PHP… for WordPress, here’s what I do:
A little explanation:
Line 1: a function is declared in which I pass by setting an address (street postal code city).
Line 2: I encode this address so that it can be integrated into a URL.
Line 3: I check if a transition with the coordinates exists. Nominatim limits access to its IAP… the transient allows you to store the information locally and not to make a request at each display… especially since the geographical coordinates of a point should not change too often….
Line 14: I create the transient that will be valid for 90 days. Basically, your WordPress will ask for geolocation only once every 90 days for the same address.
Between 2: if the address has never been geocoded then I request the Nominatim API.
Any ideas or improvements to make? Leave me a comment!
Post Thumbnail: Brett Zeck