{
"lat":38.9304552,
"lng":-77.1503227,
"txt":"Home",
"ico":"https:\/\/chart.googleapis.com\/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00CC00|000000"
}
Each JSON object represents one map point. The JSON objects will be collected into a PHP array. The array will be injected into the HTML document in the form of a json-encoded PHP string variable, using HEREDOC notation.
<?php // demo/google_javascript_map.php
/**
* Demonstrate how to use the Google Maps API for a PHP / JavaScript map
*
* Optional centered pushpin
* Optional other pushpin(s) or icons
*
* MAN PAGE: https://developers.google.com/maps/documentation/javascript/
*/
error_reporting(E_ALL);
// A CLASS TO REPRESENT A MAP POINT
Class MapPoint
{
public function __construct($lat, $lng, $txt=NULL, $ico=NULL)
{
$this->lat = $lat;
$this->lng = $lng;
$this->txt = $txt;
$this->ico = $ico;
}
}
// CREATING A ZOOM LEVEL
$zoom = '12';
// DESIGNATING OUR CENTER POINT NEAR CHAIN BRIDGE
$center = json_encode( new MapPoint( 38.929932, -77.1165074 ) );
// CREATING A COLLECTION OF MAP POINT OBJECTS
$objs = array
( new MapPoint( 38.9304552, -77.1503227, "Home", 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00CC00|000000' )
, new MapPoint( 38.9086018, -77.1298843, "Club", 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|0000CC|000000' )
, new MapPoint( 38.9400024, -77.0893293, "Church", 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|ffffff|000000' )
, new MapPoint( 38.9326919, -77.1774237, "Store", 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|CC0000|000000' )
)
;
// CREATING THE JSON STRING FROM THE ARRAY OF OBJECTS
$json = json_encode($objs);
// CREATE OUR WEB PAGE IN HTML5 FORMAT
$htm = <<<HTML5
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style type="text/css">
html, body, #map-canvas {
height:100%;
margin:0;
padding:0;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
/* COPY INJECTED PHP VARIABLES INTO OUR JAVASCRIPT VARIABLES */
var zoom = $zoom;
var center = $center;
var json = $json;
var map;
function initialize() {
var mapOptions = {
zoom: zoom,
center: new google.maps.LatLng(center)
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for(var i = 0; i < json.length; i++) {
var obj = json[i];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(obj.lat,obj.lng),
map: map,
title: obj.txt,
icon: obj.ico
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<title>E-E questions/28955215/Multiple-points-on-Google-Maps</title>
</head>
<body>
<noscript>Your browsing experience will be much better with JavaScript enabled!</noscript>
<div id="map-canvas"></div>
</body>
</html>
HTML5;
// RENDER THE WEB PAGE
echo $htm;
<?php // demo/google_javascript_interactive_map_x.php
/**
* Demonstrate how to use the Google Maps API for a PHP / JavaScript map
*
* Optional centered pushpin
* Optional other pushpin(s) or icons
* Optional toggle pushpin(s) by clickable legend icon
*
* Google API Key Information (January 2017)
* https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys
*/
error_reporting(E_ALL);
// GET YOUR OWN API KEY FROM GOOGLE
$google_api_key = GOOGLE_API;
// A CLASS TO REPRESENT A MAP POINT
Class MapPoint
{
public function __construct($lat, $lng, $txt=NULL, $ico=NULL)
{
$this->lat = $lat;
$this->lng = $lng;
$this->txt = $txt;
$this->ico = $ico;
}
}
// CREATING A ZOOM LEVEL
$zoom = '12';
// DESIGNATING OUR CENTER POINT NEAR CHAIN BRIDGE
$center = json_encode( new MapPoint( 38.929932, -77.1165074 ) );
// CREATING A COLLECTION OF MAP POINT OBJECTS
$objs = array
( new MapPoint( 38.9304552, -77.1503227, "Home", 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00CC00|000000' )
, new MapPoint( 38.9086018, -77.1298843, "Club", 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFFFF|000000' )
, new MapPoint( 38.9400024, -77.0893293, "Church", 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00|000000' )
, new MapPoint( 38.9326919, -77.1774237, "Store", 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|CC0000|000000' )
, new MapPoint( 38.872487, -77.047564, "Yacht", 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|8888FF|000000' )
, new MapPoint( 38.921519, -77.118267, "Park", 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|884400|000000' )
)
;
// CREATING THE JSON STRING FROM THE ARRAY OF OBJECTS
$json = json_encode($objs);
// USE HEREDOC NOTATION TO CREATE OUR WEB PAGE IN HTML5 FORMAT
$htm = <<<HTML5
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style type="text/css">
html, body, #map-canvas {
height:100%;
margin:0;
padding:0;
}
#legend {
font-family:Verdana, sans-serif;
background:white;
padding:1em;
margin:1em;
border:2px solid black
}
#legend h3 {
margin-top:0;
}
#legend div {
margin: 0 auto;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=$google_api_key"></script>
<script>
/* COPY INJECTED PHP VARIABLES INTO OUR JAVASCRIPT VARIABLES */
var zoom = $zoom;
var center = $center;
var json = $json;
var map;
var legend;
var legendIcon;
var gmarkers = [];
var viz;
function initialize() {
var mapOptions = {
zoom: zoom,
center: new google.maps.LatLng(center)
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
legend = document.getElementById('legend');
for(var i = 0; i < json.length; i++) {
var obj = json[i];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(obj.lat,obj.lng),
map: map,
title: obj.txt,
icon: obj.ico
});
marker.setVisible(false);
marker.id = obj.txt;
gmarkers.push(marker);
legendIcon = document.createElement('div');
legendIcon.innerHTML = '<img src="' + obj.ico + '" alt="icon" /> ' + obj.txt;
legendIcon.style.cursor = 'pointer';
legendIcon.id = obj.txt;
legendIcon.addEventListener("click", function(){
toggleIcons(this);
});
legend.appendChild(legendIcon);
}
map.controls[google.maps.ControlPosition.LEFT_TOP].push(legend);
}
function toggleIcons(icon) {
for (var i = 0; i < gmarkers.length; i++) {
if (gmarkers[i].id == icon.id) {
viz = gmarkers[i].getVisible();
if (viz) {
gmarkers[i].setVisible(false);
} else {
gmarkers[i].setVisible(true);
}
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<title>Drop / Toggle Multiple Pointers Onto Google Maps</title>
</head>
<body>
<noscript>Your browsing experience will be much better with JavaScript enabled!</noscript>
<div id="map-canvas"></div>
<div id="legend"><h3>Click an Icon</h3></div>
</body>
</html>
HTML5;
// RENDER THE WEB PAGE
echo $htm;
<?php // demo/latlng_server.php
/**
* Receive, normalize, return, and record a Geocode from a Google Map Click
* UTF-8 because the Google Maps often use JSON
* At least rooftop precision with 7 decimal places
*
* https://developers.google.com/maps/
* https://www.youtube.com/watch?v=ZE8ODPL2VPI
*/
error_reporting(E_ALL);
// SET UP PHP AND BROWSER TO USE UTF-8
mb_internal_encoding('utf-8');
mb_regex_encoding('utf-8');
mb_http_output('utf-8');
// DEFAULT RETURN SHOWS ERROR VALUE
$geo = '-0,-0';
// TERNARY OPERATOR TO GET THE GEOCODE REQUEST VARIABLE
$q
= !empty($_GET['q'])
? trim($_GET['q'])
: NULL
;
if (!$q) die($geo);
// TERNARY OPERATOR TO GET THE PRECISION REQUEST VARIABLE
$p
= !empty($_GET['p'])
? (int)trim($_GET['p'])
: 7
;
// ROUND THE VALUES OF LAT,LNG PAIR TO '$p' DECIMAL PLACES
$llp = explode(',', $q);
$llp[0] = number_format($llp[0], $p);
$llp[1] = number_format($llp[1], $p);
$geo = implode(',', $llp);
// RESPOND WITH THE NORMALIZED GEOCODE
echo $geo;
// ADDITIONAL PROCESSING (MAYBE STORE IN DATABASE HERE)
$date = date('c');
$user = $_SERVER['REMOTE_ADDR'];
$mesg = "Geocode $date $user $geo";
<?php // demo/latlng_client.php
/**
* Click to drop a pin onto a Google Map
* Get the Geocode from Google and make an AJAX request
* The server will normalize decimal values for lat,lng
*
* Google API Key Information (January 2017)
* https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys
*/
error_reporting(E_ALL);
// SET UP PHP AND BROWSER TO USE UTF-8
mb_internal_encoding('utf-8');
mb_regex_encoding('utf-8');
mb_http_output('utf-8');
// GET YOUR OWN API KEY FROM GOOGLE
$google_api_key = GOOGLE_API;
// CREATE THE WEB PAGE DOCUMENT USING PHP HEREDOC NOTATION
$html = <<<HTML
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
html, body {
padding:0;
margin:0;
height: 100%;
overflow:hidden;
}
#map {
width:100%;
height:100%;
}
#dataset {
position:absolute;
font-size:2em;
z-index:5;
top:2em;
opacity:0.8;
width:100%;
text-align:center;
display:block;
color:white;
margin:0 auto;
}
#origin {
background-color:green;
}
#target {
background-color:red;
}
</style>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<!-- Map Script -->
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=$google_api_key"></script>
<script>
var map;
var geocode;
var marker = null;
function mapinit() {
var mapOptions = {
zoom: 5,
disableDefaultUI: false,
center: new google.maps.LatLng(38.95939,-95.2654831), // Google Earth Center of USA in Lawrence, KS
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
geocode = event.latLng.lat() + "," + event.latLng.lng();
$("#origin").html('GoogleMaps geocode: ' + geocode);
$.get("latlng_server.php", {q:geocode,p:7}, function(response){
$("#target").html('Normalized geocode: ' + response);
});
if (marker) { // Remove old marker
marker.setMap(null);
}
marker = new google.maps.Marker({ position: event.latLng, map: map});
});
}
google.maps.event.addDomListener(window, 'load', mapinit);
</script>
<title>Latitude and Longitude (Geocode) via Google Maps Click</title>
</head>
<body>
<div id="dataset">
<div id="origin"></div>
<div id="target"></div>
</div>
<div id="map"></div>
</body>
</html>
HTML;
echo $html;
<?php // demo/google_static_map_class.php
/**
* Demonstrate how to use the Google Maps API for a static map of specific size
*
* Optional centered pushpin
* Optional other pushpin(s) or icons
*
* MAN PAGE: http://code.google.com/apis/maps/documentation/staticmaps/
*/
error_reporting(E_ALL);
class GSM
{
// THE MAP CENTER GEOCODE, ADDRESS OR LANDMARK
protected $center;
// MARKER DATA ARRAY
protected $markers;
protected $default_icon;
// OUR VARIABLES FOR THE MAP DISPLAY
protected $maptype;
protected $width;
protected $height;
protected $zoom;
protected $format;
// OUR VARIABLES FOR THE GOOGLE URL AND IMAGE TAG
protected $alt;
protected $title;
protected $class;
protected $id;
protected $usemap;
protected $sensor;
protected $url;
private $img;
// A CONSTRUCTOR TO SET THE DEFAULT VALUES
public function __construct()
{
// THE URL AND IMG TAG PARAMETERS
$this->alt = FALSE;
$this->class = FALSE;
$this->id = FALSE;
$this->usemap = FALSE;
$this->sensor = FALSE;
$this->title = TRUE;
$this->url = '';
$this->img = '';
// THE CENTER AND ZOOM SCALE OF THE MAP (IF OMITTED, GOOGLE WILL CALCULATE)
$this->center = NULL;
$this->zoom = NULL;
// THE CHARACTERISTICS OF THE MAP IMAGE
$this->maptype = 'hybrid'; // CHOOSE
$this->maptype = 'terrain'; // AMONG
$this->maptype = 'satellite'; // THESE
$this->maptype = 'roadmap'; // OPTIONS
$this->width = '640';
$this->height = '640';
$this->format = 'png';
// THE DEFAULT ICON
$this->default_icon = 'http://maps.google.com/mapfiles/ms/micons/question.png';
// AN ARRAY OF MARKER ARRAYS
$this->clearMarkers();
} // END CONSTRUCTOR
// A METHOD TO CLEAR THE MARKERS
public function clearMarkers()
{
$this->markers = array();
}
// A SETTER TO ADD MARKERS TO THE MAP
public function setMarker($geocode, $color='blue', $label='X')
{
// NOTE THAT THIS WILL WORK CORRECTLY MOST OF THE TIME
$geocode = urlencode(urldecode($geocode));
$this->markers[]
= array
( 'color' => $color
, 'label' => $label
, 'geocode' => $geocode
, 'icon' => FALSE
)
;
}
// A SETTER TO ADD ICONS TO THE MAP - VIEW SOURCE HERE: http://www.visual-case.it/cgi-bin/vc/GMapsIcons.pl
public function setIcon($geocode, $icon=FALSE)
{
// NOTE THAT THIS WILL WORK CORRECTLY MOST OF THE TIME
$geocode = urlencode(urldecode($geocode));
if (!$icon) $icon = $this->default_icon;
$this->markers[]
= array
( 'color' => FALSE
, 'label' => FALSE
, 'geocode' => $geocode
, 'icon' => $icon
)
;
}
// A SETTER TO OVERRIDE EACH OF THE DEFAULT VALUES
public function setCenter($geocode=NULL)
{
// NOTE THAT THIS WILL WORK CORRECTLY MOST OF THE TIME
$geocode = urlencode(urldecode($geocode));
$this->center = $geocode;
}
public function setMaptype($x)
{
$this->maptype = $x;
}
public function setFormat($x)
{
$this->format = $x;
}
public function setWidth($x)
{
$this->width = $x;
}
public function setHeight($x)
{
$this->height = $x;
}
public function setZoom($x=NULL)
{
$this->zoom = $x;
}
public function setAlt($x=FALSE)
{
$this->alt = $x;
}
public function setTitle($x=TRUE)
{
$this->title = $x;
}
public function setClass($x=FALSE)
{
$this->class = $x;
}
public function setId($x=FALSE)
{
$this->id = $x;
}
public function setUsemap($x=FALSE)
{
$this->usemap = $x;
}
public function setSensor($x=FALSE)
{
$this->sensor = $x;
}
// A METHOD TO PREPARE AND RETRIEVE THE MAPPING URL
public function asURL()
{
$s = 'false'; // SEE http://code.google.com/apis/maps/documentation/staticmaps/#Sensor
if ($this->sensor) $s = 'true';
// IF ICONS OR MARKERS ARE ON THE MAP, 'IMPLODE' THE DATA INTO THE URL
$marker_string = '';
foreach ($this->markers as $marker)
{
// PROCESS FOR CUSTOM ICONS
if ($marker['icon'])
{
$marker_string
= $marker_string
. '&markers='
. 'icon:'
. urlencode($marker['icon'])
. '|'
. $marker['geocode']
;
continue;
}
// PROCESS FOR STANDARD MARKERS
$marker_string
= $marker_string
. '&markers='
. 'color:'
. $marker['color']
. '|'
. 'label:'
. $marker['label']
. '|'
. $marker['geocode']
;
}
// SET CENTER AND ZOOM, IF PRESENT
$c = '';
if ($this->center) $c = "¢er=$this->center";
$z = '';
if ($this->zoom) $z = "&zoom=$this->zoom";
// MAKE THE URL
$this->url
= "http://maps.google.com/maps/api/staticmap?sensor=$s"
. $c
. $z
. "&size=$this->width" . 'x' . "$this->height"
. "&format=$this->format"
. "&maptype=$this->maptype"
. "$marker_string"
;
return $this->url;
}
// A METHOD TO PREPARE AND RETRIEVE THE HTML IMAGE TAG
public function asIMG()
{
// GET THE URL
if (!$this->url) $this->url = $this->asURL();
// GET THE ALT TEXT
$a = "$this->maptype" . ' centered ' . "$this->center";
if ($this->alt !== FALSE) $a = $this->alt;
// REQUIRED FIELDS
$this->img = '<img src="' . $this->url . '" alt="' . $a . '"';
// OPTIONAL FIELDS - PROVIDE A DEFAULT TITLE
$t = "$this->maptype" . ' centered ' . "$this->center";
if ($this->title === TRUE ) { $this->img .= ' title="' . $t . '"'; }
elseif ($this->title !== FALSE) { $this->img .= ' title="' . $this->title . '"'; }
// OPTIONAL FIELDS MAY BE OMITTED
if ($this->class !== FALSE) { $this->img .= ' class="' . $this->class . '"'; }
if ($this->id !== FALSE) { $this->img .= ' id="' . $this->id . '"'; }
if ($this->usemap !== FALSE) { $this->img .= ' usemap="' . $this->usemap . '"'; }
// CLOSE THE IMAGE TAG AND CLEAR THE CONSUMED URL
$this->img .= ' />';
$this->url = FALSE;
return $this->img;
}
} // END CLASS
// MAKE A GOOGLE STATIC MAP OBJECT AND TEST IT OUT
$map = new GSM;
$map->setWidth(620);
$map->setHeight(620);
$map->setZoom(12);
// SET A CENTER POINT (BUT NO MARKER) BY LANDMARK NAME ALONE
// $map->setCenter("THE WHITE HOUSE");
// SET A MARKER BY GEOCODE (LAT/LON PAIR)
$map->setMarker("38.930387,-77.147777", 'green', 'H');
// SET A MARKER BY PLACE NAME, CITY, STATE
$map->setMarker("Landon School, Bethesda, MD", 'brown', 'L');
// SET A MARKER BY STREET ADDRESS AND ZIP CODE
$map->setMarker("1446 Colleen Lane 22101", 'orange', 'P');
// ECHO THE <img /> TAG INTO OUR HTML TO DRAW THE MAP
echo $map->asIMG();
echo PHP_EOL . '<br clear="all" />';
// SHOW THE OBJECT
echo "<pre>" . PHP_EOL;
print_r($map);
echo"</pre>" . PHP_EOL;
// USE THE GSM OBJECT TO DRAW ANOTHER MAP WITH A SWIMMER IN THE TIDAL BASIN
$map->clearMarkers();
$map->setZoom();
$map->setWidth(500);
$map->setHeight(400);
$map->setCenter("THE US CAPITOL, WASHINGTON DC");
$map->setMarker("THE WHITE HOUSE", 'red', 'W');
$map->setMarker("THE US CAPITOL, WASHINGTON DC", 'blue', 'C');
$map->setIcon("THE TIDAL BASIN, WASHINGTON DC", 'http://maps.google.com/mapfiles/ms/micons/swimming.png', 'false'); // NO SHADOW
echo $map->asIMG();
// SHOW THE OBJECT
echo "<pre>" . PHP_EOL;
print_r($map);
echo"</pre>" . PHP_EOL;
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (7)
Commented:
Good point about the features that would be left out with the static image. I had forgotten about them even though I am sure they would be something a developer may not want to omit. As you said, a "compromise".
Sort of nice to know there is an option that could be a quick way to provide a map. Without the need to get a key this may be something perfect for someone who just wants a simple map.
bol
Commented:
This is not usefull for me .Every expert is giving same code but this is not my requirement .In this code no infoWindow display.
I want to this type functionality :
see here : http://www.ifc.org/ifcext/spiwebsite1.nsf/$$MapView?openform
Thanks and Regards
Aasim Afridi
Author
Commented:Commented:
Could you please suggest which one to use Static map or javascript based map? I have a requirement like display multiple address with custom icon (it is simlar airbnb browse & display location details?)
Author
Commented:View More