Geolocation and Maps in PHP: Libraries, API, and Code Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Geolocation and Maps in PHP: Tools Overview and Code Examples



In modern web development, geolocation and map functionality have become an integral part of many projects. PHP, being a server-side language, handles geodata processing, integration of mapping services, and user location determination perfectly. In this article, we will thoroughly review the main libraries and tools for working with geolocation and maps in PHP, and provide practical code examples.



1. Determining Location by IP Address (GeoIP)



The simplest way to get a user's approximate geolocation is to determine their country and city by IP address. For this, there are several solutions in PHP:



geoip2 Library (MaxMind GeoIP2)



MaxMind provides a free GeoLite2 database and a paid GeoIP2 database. Installation via Composer:



composer require geoip2/geoip2


Example of determining location:



<?phprequire_once 'vendor/autoload.php';

use GeoIp2\\Database\\Reader;

// Specify the path to the downloaded GeoLite2-City.mmdb database$reader = new Reader('/path/to/GeoLite2-City.mmdb');$record = $reader->city('8.8.8.8'); // IP address to check

echo "Country: " . $record->country->name . "<br>";echo "City: " . $record->city->name . "<br>";echo "Latitude: " . $record->location->latitude . "<br>";echo "Longitude: " . $record->location->longitude . "<br>";?>


Built-in geoip_record_by_name() Function



If the GeoIP extension (deprecated) is installed on the server, you can use:



<?php$record = geoip_record_by_name('8.8.8.8');echo "City: " . $record['city'];?>


2. Working with Maps via JavaScript + PHP



PHP generates HTML/JavaScript, while map rendering happens on the client side. The most popular libraries:



  • Leaflet — lightweight, free, no API keys required
  • OpenLayers — powerful, for complex geospatial tasks
  • Google Maps JavaScript API — requires a key, but provides rich functionality


Example of Leaflet Integration with PHP



Let's create a simple map with a marker whose coordinates are passed from PHP:



<?php$lat = 55.7558;  // Moscow$lng = 37.6173;?><!DOCTYPE html><html><head>    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script></head><body>    <div id="map" style="height: 400px; width: 100%;"></div>    <script>        var map = L.map('map').setView([<?= $lat ?>, <?= $lng ?>], 10);        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {            attribution: '&copy; OpenStreetMap contributors'        }).addTo(map);        L.marker([<?= $lat ?>, <?= $lng ?>]).addTo(map)            .bindPopup('Marker from PHP');    </script></body></html>


3. Geocoding (Converting Address to Coordinates)



To get coordinates from an address, use APIs:



  • Nominatim (OpenStreetMap) — free, but with limitations (1 request per second)
  • Google Geocoding API — paid after exceeding the limit
  • Yandex Geocoder — popular in Russia


Example of Geocoding via Nominatim



<?phpfunction geocode($address) {    $url = "https://nominatim.openstreetmap.org/search?format=json&q=" . urlencode($address);    $opts = [        'http' => [            'method' => 'GET',            'header' => "User-Agent: MyApp/1.0\\r"                    

Recommendations