获取网络访问者的确切国家和城市(以drupal 8或PHP原生)

I need for my website to know the real and accurate location of a visitor to offer him / her near elements.

I am trying to consume various external services and they tell me that I am located in barcelona (when I l live in Madrid).

These are the services I am consuming:

Know any service or any way in PHP to get exact location data?

I am afraid this is not possible.

The best way to go about solving this is to use javascript and get longitude and latitude from the visitor of your site. This, of course, requires the visitors device to have such abilities. Read more about this at MDN web docs.

If your visitors device does not support this method, use IP Geo location as a fallback. The problem with this is that it is not reliable as you have discovered. I live near Bergen in Norway, and if I use IP to geolocate my phone, it always shows that I am in Oslo. This is due to my cell phone operator of course, but this is also a problem with other services giving you IP addresses. You can read more about how accurate IP Geo location is at WhatsMyIPAddress.com.

Lastly, always give the user the ability to give you their location when visiting your site.

You can try using our new geo location api https://ip-api.io/

In php it could work like this:

$ipAddress = $_SERVER['REMOTE_ADDR'];
if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
    $ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
}
$data = json_decode(file_get_contents("http://ip-api.io/api/json/$ipAddress"));
var_dump($data);