Solved

Google Maps Multiple Markers

Posted on 2010-11-29
12
1,359 Views
Last Modified: 2012-08-13
Hi,
I call my location, name and image from my db and plot it on a google map.  I can't figure out how to have it show my contacts as well.  I am using google maps v3.  I have all my contacts (name, location and image) echo'd to screen already, I just need the markers to plot themselves based on the contacts current_location.
Can someone help me please?

snippet (of my contact data that is echo'd):

foreach( $result as $contacts)
    {
          echo $contacts['first_name'].' '.$contacts['last_name'].' '.$contacts['current_location']['name'].' '.$contacts['pic']. '<br>';
            
    }

var me = <?php echo json_encode( $me ); ?>;
var geocoder;
var map;
var address = me['location']['name'];
var name = me['first_name'] + " " + me['last_name'];
var pic = '<img src="' + me['pic'] + '" height="60px"';

function initialize() {
 geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 6,
      center: latlng,
    mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
      mapTypeId: google.maps.MapTypeId.TERRAIN
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

	
    if (geocoder) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);

            var infowindow = new google.maps.InfoWindow(
                { content: '<p>'+pic+'</p>',
                  size: new google.maps.Size(150,50)
                });
		
            var marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map, 
                title:name
            }); 
            google.maps.event.addListener(marker, 'click', function() {
                infowindow.open(map,marker);
            });

          } else {
            alert("No results found");
          }
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }
  }

Open in new window

0
Comment
Question by:MsKrissy
  • 6
  • 5
12 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34238089
Please have a look at this article.  You can do it all with REST services and Google will render the map image right into your HTML.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_3350-Using-the-Google-Maps-API-in-PHP.html
0
 
LVL 28

Expert Comment

by:strickdd
ID: 34238872
new google.maps.Marker({
      position: LAT_LONG,
      map: map,
      icon:  new google.maps.MarkerImage(IMAGE_URL,
      new google.maps.Size(60, 60))
  });
0
 

Author Comment

by:MsKrissy
ID: 34241681
Okay, I have made the following changes, but I am still stuck.  What am I doing wrong.

Note:
I am trying to use address' (Logan Utah instead of latLng)

 

var me = <?php echo json_encode( $me ); ?>;
var geocoder;
var map;
//var address = me['location']['name'];
var name = me['first_name'] + " " + me['last_name'];
var pic = '<img src="' + me['pic'] + '" height="60px"';

function initialize() {
 geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(34.44, 117.10);
    var myOptions = {
      zoom: 6,
      center: latlng,
    mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
      mapTypeId: google.maps.MapTypeId.TERRAIN
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

	
    if (geocoder) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);

            var infowindow = new google.maps.InfoWindow(
                { content: '<p>'+pic+'</p>',
                  size: new google.maps.Size(150,50)
                });

    
            var marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map, 
                title:name
            }); 
            google.maps.event.addListener(marker, 'click', function() {
                infowindow.open(map,marker);
            });

          } else {
            alert("No results found");
          }
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }
  }

/////////////////////////////////////////////////////NEW CODE ADDED TO PLOT MULTIPLE MARKERS///////////////////////////
var NewMarkers = new Array();
  function addMarkers()
  {
  var Address ="<?php echo $contacts['current_location']['name'].";" ?>";
  var Name ="<?php echo $full_name; ?> "; 
  var Pic ="<?php echo "<img src=$contacts[pic] height=60px >"; ?>"; 
  
for (i=0; i<Address.length; i++)
  {
  if (Address[i] != "")
  {
    // add marker
            var marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map, 
                title:Name
    });
	var infowindow = new google.maps.InfoWindow(
                { content: '<p>'+Pic+'</p>',
                  size: new google.maps.Size(150,50)
                });
    NewMarkers[i] = marker;

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34247285
What address in Logan Utah?  I will show an example.
0
 

Author Comment

by:MsKrissy
ID: 34249222
Here is the address,

Address: 1400 Old Main Hill
Logan, Utah 84322-1400
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34250551
Moving parts start at about line 245.  You can add other markers / icons by either address or lat/lon pair with the setMarker() or setIcon() methods.
<?php // RAY_google_static_map_class.php

error_reporting(E_ALL);



// 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/



// DEFINE THE GOOGLE STATIC MAPPING CLASS

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', $shadow='true')

    {

        $this->markers[]

        = array

        ( 'color'   => $color

        , 'label'   => $label

        , 'shadow'  => $shadow

        , '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, $shadow='true')

    {

        if (!$icon) $icon = $this->default_icon;

        $this->markers[]

        = array

        ( 'color'   => FALSE

        , 'label'   => FALSE

        , 'shadow'  => $shadow

        , 'geocode' => $geocode

        , 'icon'    => $icon

        )

        ;

    }



    // A SETTER TO OVERRIDE EACH OF THE DEFAULT VALUES

    public function setCenter($geocode=NULL)

    {

        $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'])

                . '|'

                . 'shadow:'

                . urlencode($marker['shadow'])

                . '|'

                . $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 = "&center=$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

$x = new GSM;

$x->setWidth(620);

$x->setHeight(620);

$x->setZoom(12);



// SET A CENTER POINT (BUT NO MARKER) BY ADDRESS

$x->setCenter("1400 Old Main Hill, Logan, Utah 84322-1400");



// SET A SNOWFLAKE AT THE CENTER POINT, WITH A DROP SHADOW

$x->setIcon("1400 Old Main Hill, Logan, Utah 84322-1400", 'http://maps.google.com/mapfiles/ms/micons/snowflake_simple.png');



// ECHO THE <img /> TAG INTO OUR HTML TO DRAW THE MAP

echo $x->asIMG();

Open in new window

0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Author Comment

by:MsKrissy
ID: 34250794
Thank you so much, this was very helpful.  What if I wanted to add additional markers from variables that are stored in my sql db?  I currently have them echoing to screen like so:

foreach( $result as $contacts)
    {
          echo $contacts['first_name'].' '.$contacts['last_name'].' '.$contacts['current_location']['name'].' '.$contacts['pic']. '<br>';
           
    }
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34250844
Does this contain an address?
$contacts['current_location']['name']
0
 

Author Comment

by:MsKrissy
ID: 34251127
yeah it does.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 34251715
Check the code snippet at line 257.  You can repeat the calls to the setIcon() method with new addresses as many times as you want, within the limits of the length of the allowable GET string.  Not sure how many times this will be, but I would expect lots.
0
 

Author Closing Comment

by:MsKrissy
ID: 34259554
Thank you for the help, I really appreciate your time.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34259643
Thanks for the points -- glad I could help, ~Ray
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now