How do I get the Visitor Geo Location data from the Visitor IP? (or in JavaScript/JSON when IP address is not known)
In Matomo (Piwik) we recommend to configure Geo Location so that your visitors are accurately tracked. Once it is setup, you can use a geolocation database to get an IP to Country, or IP to City, or IP to Region information. We have added a simple API that you can re-use, called UserCountry.getLocationFromIP
.
To use it, go to Matomo, click API, click on “UserCountry” then on the getLocationFromIp call.
Click to see a typical response from the UserCountry.getLocationFromIP
API call.
You may use this simple Web API provided by Matomo to add geo location functionality to your Apps, for example.
JavaScript / JSON API to get the visitor geo location without knowing the IP address
Since Matomo 3.10.0 you can also use this API in JavaScript / JSON by simply calling the API without specifying the ip
URL parameter. This is valuable because when you’re running in the browser in JavaScript it is not possible to get the IP address. So by simply calling this API: https://analytics.example.comorg/?module=API&method=UserCountry.getLocationFromIP&format=json
in JavaScript you will get the geo location data for the current user requesting this request. This would be useful when you want to personalise the website’s content based on the user’s geolocation for example. Notes:
- This will work only when anonymous access is enabled and has access to at least one website.
- because this API request takes around 200ms or more, this is too slow for your website to depend on this request to personalise content. We would only recommend it when personalising elements on the page that are optional (after the main page was loaded) to ensure your website loads quickly.