Php

Google Maps Routes between two places with PHP & JS

in this post, we’ll be going to implement how to draw the path on the map between two locations using Google Map Javascript API. You can use routes on Google Maps for a location-based service, a delivery tracking system, or simply helping users navigate.

We’ll use the JavaScript library Direction service to draw routes between locations.

What’s Google Map API

Google Maps provides a set of APIs that allow developers to embed maps into web pages, create custom markers, and, importantly, generate routes between locations.

Google Maps Routes Using PHP and JS

Let’s explore how to create routes on Google Maps using PHP.

How To Get Google Map API Key

First, You need to obtain a Google Maps API key. You need to visit the Google Cloud Console and create a new project, then enable the “Maps JavaScript API,” and generate your API key.

HTML Page

Let’s create a Google HTML page to view a map with routes. We’ll include the Google Maps JavaScript API and set up a map container.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Google Maps Routes with PHP</title>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
    <style>
        #map {
            height: 400px;
            width: 100%;
        }
    </style>
</head>
<body>
    <div id="map"></div>
    <script>
        function initMap() {
            // Your map initialization code here
        }
    </script>
</body>
</html>

You need to replace YOUR_API_KEY with the API key you obtained from the Google Cloud Console.

Initializing a Google Map

Let’s initialize a basic map for a Denver location. We have passed lat and lng for Denver city.

Related Post
function initMap() {
    const map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: 39.7348, lng: -104.9653 }, // Denver coordinates
        zoom: 12
    });
}

You can replace the coordinates and zoom level according to your preferences.

Adding Markers

Let’s enhance the map by adding markers, Added to markers into the map. We’ll modify the initMap function to include markers:

function initMap() {
    const map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: 39.7348, lng: -104.9653 },
        zoom: 12
    });

    // Add markers
    const marker1 = new google.maps.Marker({
        position: { lat: 39.7348, lng: -104.9653 },
        map: map,
        title: 'Marker 1'
    });

    const marker2 = new google.maps.Marker({
        position: { lat: 39.546800, lng: -105.095823 },
        map: map,
        title: 'Marker 2'
    });
}

Replace positions and titles as per your requirements.

Generating Routes with PHP

Let’s create a simple PHP script that calculates and returns a route between two locations. We’ll leverage the Directions API provided by Google Maps to generate dynamic routes using PHP.

<?php
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $origin = urlencode($_GET['origin']);
    $destination = urlencode($_GET['destination']);
    $api_key = 'YOUR_API_KEY'; // Replace with your Google Maps API key

    $url = "https://maps.googleapis.com/maps/api/directions/json?origin=$origin&destination=$destination&key=$api_key";

    $response = file_get_contents($url);

    header('Content-Type: application/json');
    echo $response;
}
?>

Integrating PHP with JavaScript

Finally, modify the JavaScript code in your HTML file to fetch and display the route on the map.

function initMap() {
 // Inside initMap function
 const directionsService = new google.maps.DirectionsService();
 const directionsRenderer = new google.maps.DirectionsRenderer();

    const map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: 39.7348, lng: -104.9653 },
        zoom: 12
    });

    // Add markers
    const marker1 = new google.maps.Marker({
        position: { lat: 39.7348, lng: -104.9653 },
        map: map,
        title: 'Marker 1'
    });

    const marker2 = new google.maps.Marker({
        position: { lat: 39.546800, lng: -105.095823 },
        map: map,
        title: 'Marker 2'
    });
 
 directionsRenderer.setMap(map);

 const request = {
  origin: 'Denver, Colorado, USA',
  destination: 'Denver Botanic Gardens, 1007 York St, Denver, CO 80206, United States',
  travelMode: 'DRIVING'
 };

 directionsService.route(request, function(response, status) {
  if (status === 'OK') {
   directionsRenderer.setDirections(response);
  }
 });
}

Replace the origin and destination values based on your needs.

Conclusion:

We have learned javascript Google Map API and integrated it with PHP. We have created a map and added markers. We have defined routes between the locations using Google Maps. You can change travelMode, source and destination as per your need.

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

4 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

10 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

10 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

10 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

11 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

11 months ago

Categories