Google Map with a Marker with PHP & Google Map API

These php tutorials help to understand google map and the integration google map JavaScript API using PHP and jQuery. We will create a map using a constant address and get coordinates to display markers on that location.

MAP is a very important functionality to display the direction of address on the contact us page, You can also add a map into the wiki to tell the direction of your business location.Google provides google map to create a map for your location, google also provides map API for accessing to google maps methods and functionality features.

Google provides google map js libs to access map methods using API, We will use a static city names and get latitude and longitude using google map API, then we will send latitude and longitude to the map instance to display map. The Google map has a Zoom level for the map, the zoom value varies between 1 and 20, 20 being the most zoomed-in value, and 1 being the most zoomed-out.

google-map-api-with-php

Let’s Start to Add Google Map Using PHP

This PHP tutorial helps to display a simple google map with a marker to a web web page. We will use some HTML, CSS, and JavaScript code to display the map. For an advanced guide to creating maps, read the developer’s guide. There are following steps will follow in this google map tutorial,

  • Get a Google Map API key.
  • We will create a div that will display the map.
  • We will create API wrapper in PHP that will get formatted address, latitude and longitude using the City name
  • We will create an Ajax request that will call the above PHP API and pass data to the google map instance.

The file structure is,

  • index.php : This file will have all CSS, JavaScript, and HTML code.
  • map_api_wrapper.php : This file will use to create a method to get latitude and longitude.

How to get Google API Key

  • Go to the Google API Console
  • Create or select a project.
  • Click Continue to enable the API and any related services.
  • Now Credentials page will open and get the key.

How To Check Your API Key

To verify a Google Maps API key, you can perform a simple test by making a request to a Google Maps API endpoint.

<!DOCTYPE html>
<html>
<head>
  <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
</head>
<body>
  <div id="map"></div>
  <script>
    function initMap() {
      const map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: 39.7392, lng: -104.9903 },
        zoom: 8
      });
    }
  </script>
</body>
</html>

Replace YOUR_API_KEY with your actual Google Maps API key in the <script> tag’s src attribute. Open this HTML file in a web browser. If the map displays correctly, it means your API key is working.

Let’s integrate Google map with our application.

Step 1: We will created index.php file added below HTML code into this file.

<title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
     	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
	<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
<div id="map"></div>

We have included bootstrap and jquery libs into the head section of this file, created a div container id is ‘#map’, this div will responsible to display a map, Also Added some CSS for the map div container.

Step 2: We create map_api_wrapper.php file that will use google API to get latitude and longitude using City name, added below code into this file.

<?php
function get_geocode($address){
 
    // url encode the address
    $address = urlencode($address);
    
    // google map geocode api url
    $url = "http://maps.google.com/maps/api/geocode/json?address={$address}";
 
    // get the json response from url
    $resp_json = file_get_contents($url);
    
    // decode the json response
    $resp = json_decode($resp_json, true);
    // response status will be 'OK', if able to geocode given address
    if($resp['status']=='OK'){
    	//define empty array
 		$data_arr = array(); 
        // get the important data
        $data_arr['latitude'] = isset($resp['results'][0]['geometry']['location']['lat']) ? $resp['results'][0]['geometry']['location']['lat'] : '';
        $data_arr['longitude'] = isset($resp['results'][0]['geometry']['location']['lng']) ? $resp['results'][0]['geometry']['location']['lng'] : '';
        $data_arr['formatted_address'] = isset($resp['results'][0]['formatted_address']) ? $resp['results'][0]['formatted_address'] : '';
        
        // verify if data is exist
        if(!empty($data_arr) && !empty($data_arr['latitude']) && !empty($data_arr['longitude'])){

            return $data_arr;
            
        }else{
            return false;
        }
        
    }else{
        return false;
    }
}
echo json_encode(get_geocode('denver'));
?>

created get_geocode() method that takes an address as a parameter, fetch data from google API using address. We called get_geocode() method at the end of the file that response address information as a JSON data.

Step 3: We will create an AJAX call to fetch data from map_api_wrapper.php file and send the map function to display map. We will add the below code into the footer of the index.php file.

<script type="text/javascript">
  var map;
  function getData() {
    $.ajax({
    url: "map_api_wrapper.php",
    async: true,
    dataType: 'json',
    success: function (data) {
      console.log(data);
      //load map
      init_map(data);
    }
  });  
  }
  
  function init_map(data) {
        var map_options = {
            zoom: 14,
            center: new google.maps.LatLng(data['latitude'], data['longitude'])
          }
        map = new google.maps.Map(document.getElementById("map"), map_options);
       marker = new google.maps.Marker({
            map: map,
            position: new google.maps.LatLng(data['latitude'], data['longitude'])
        });
        infowindow = new google.maps.InfoWindow({
            content: data['formatted_address']
        });
        google.maps.event.addListener(marker, "click", function () {
            infowindow.open(map, marker);
        });
        infowindow.open(map, marker);
    }
    

<script src="https://maps.googleapis.com/maps/api/js?key=api_key&callback=getData" async defer></script>

Created AJAX call to fetch data from the map_api_wrapper file.

Added google map JavaScript API at the end of the file, this file uses the google API key and initializes map method. You need to replace API key with your API key. The callback parameter executes the get_geocode() function after the Google map JavaScript API loads. The async attribute allows the browser to continue rendering the rest of your page while the API loads.

We are using a JavaScript getElementById() function to find the map div on the web page.

The new google.maps.Map() creates a new Google maps object. The center property tells the API where to center the map. The map coordinates are set in the order: of latitude, and longitude. The map includes the center and zoom level of the location.

Conclusion:

We have created a google map using google javascript map API, We have also set markers into the map. You can also set other properties of map as well, this is a basic PHP tutorial to help out adding map with a marker using google javascript map API.

You can download the source code and see Demo the below link.

9 thoughts on “Google Map with a Marker with PHP & Google Map API

  1. Thank you. But is not working.
    Link of download source button: https://phpflow.com/source_code/google_map_api_with_php_source/google_map_api_with_php_source.zip
    Error: Oops! That page can’t be found.
    It looks like nothing was found at this location. Maybe try one of the links below or a search?

  2. Hi

    I have tested your code exactly as you show it, using a good Google api key. I’m getting a blank screen just I get w/ similar javascript code to yours but much simplier (I can send the simple code upon request)

    Any thoughts?? Did Google change something?

    ~Steve

    • You need to set your API key, first time google is providing some $ credit into your account you can use it, after that you need to set billing information otherwise you will get message : “You must enable Billing on the Google Cloud Project”.

Leave a Reply

Your email address will not be published.