Saturday, April 6, 2013

Add Marker with Label for Google Maps API V3



For last couple of days I was searching for Google Map Marker with Label functionality then I found the following PHP class in PHP Google Maps API. I did use this class for both CakePHP and conventional PHP.

This class really help me to integrate the goole map advance features easily in my real estate application. but one feature was missing in the library and that was Label in marker. 

I need that label to show the property price in the marker. I start searching for the feature and finally I found it in the following address

http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.1.8/docs/examples.html

After 1-2 hours dig down in the script I have decided to integrate this feature in the PHP Google Maps API.

What I did is here I am trying to share with you...

Added the following variables for the class..

var $marker_with_label = true;

var $marker_label_js = "js/gmap/markerwithlabel.js";


Update the functions as like below


function getHeaderJS() { 
    if($this->marker_with_label){
    $_headerJS .= "";
    }
}

function getUtilityFunctions(){
   $_script = "";
   if(!empty($this->_markers)&& $this->marker_with_label)
    $_script .= $this->getCreateMarkerWithLabelJS();
         else
             $_script .= $this->getCreateMarkerJS();
}

function getAddMarkersJS($map_id = "", $pano= false) {
  //defaults
  if($map_id == ""){
   $map_id = $this->map_id;
  }
  
  if($pano==false){
   $_prefix = "map";
  }else{
   $_prefix = "panorama".$this->street_view_dom_id;
  }
        $_output = '';
        foreach($this->_markers as $_marker) {

            $iw_html = str_replace('"','\"',str_replace(array("\n", "\r"), "", $_marker['html']));
            $_output .= "var point = new google.maps.LatLng(".$_marker['lat'].",".$_marker['lon'].");\n";
            if($this->marker_with_label){
                $_output .= sprintf('%s.push(createMarkerWithLabel(%s%s, point,"%s","%s", %s, %s, "%s", %s, "%s" ));',
                    (($pano==true)?$_prefix:"")."markers".$map_id,
                    $_prefix,
                    $map_id,
                    str_replace('"','\"',$_marker['title']),
                    str_replace('/','\/',$iw_html),
                    (isset($_marker["icon_key"]))?"icon".$map_id."['".$_marker["icon_key"]."'].image":"''",
                    (isset($_marker["icon_key"])&&isset($_marker["shadow_icon"]))?"icon".$map_id."['".$_marker["icon_key"]."'].shadow":"''",
                    (($this->sidebar)?$this->sidebar_id:""),
                    ((isset($_marker["openers"])&&count($_marker["openers"])>0)?json_encode($_marker["openers"]):"''"),
                    (string)$_marker['price']
                ) . "\n";
            }
           else
           {
               $_output .= sprintf('%s.push(createMarker(%s%s, point,"%s","%s", %s, %s, "%s", %s ));',
                   (($pano==true)?$_prefix:"")."markers".$map_id,
                   $_prefix,
                   $map_id,
                   str_replace('"','\"',$_marker['title']),
                   str_replace('/','\/',$iw_html),
                   (isset($_marker["icon_key"]))?"icon".$map_id."['".$_marker["icon_key"]."'].image":"''",
                   (isset($_marker["icon_key"])&&isset($_marker["shadow_icon"]))?"icon".$map_id."['".$_marker["icon_key"]."'].shadow":"''",
                   (($this->sidebar)?$this->sidebar_id:""),
                   ((isset($_marker["openers"])&&count($_marker["openers"])>0)?json_encode($_marker["openers"]):"''")
               ) . "\n";
           }


        }
        
        if($this->marker_clusterer && $pano==false){//only do marker clusterer for map, not streetview
         $_output .= "
            markerClusterer".$map_id." = new MarkerClusterer(".$_prefix.$map_id.", markers".$map_id.", {
            maxZoom: ".$this->marker_clusterer_options["maxZoom"].",
            gridSize: ".$this->marker_clusterer_options["gridSize"].",
            styles: ".$this->marker_clusterer_options["styles"]."
          });
           
         ";
        }
        return $_output;
    }

function getCreateMarkerWithLabelJS(){
        $_output = "
        function createMarkerWithLabel(map, point, title, html, icon, icon_shadow, sidebar_id, openers,label){

        var marker1 = new MarkerWithLabel({
                   position: point,
                   map: map,
                   labelContent:'$'+label ,
                   labelAnchor: new google.maps.Point(22, 10),
                   labelClass: 'labels', // the CSS class for the label
                   icon:icon,
                   shadow:icon_shadow
                 });

       //if(icon!=''){marker_options.icon = icon;}
       //if(icon_shadow!=''){marker_options.shadow = icon_shadow;}

       //create marker
       //var new_marker = new google.maps.Marker(marker_options);
       if(html!=''){
     ".(($this->info_window)?"

           google.maps.event.addListener(marker1, '".$this->window_trigger."', function() {
              infowindow.close();
              infowindow.setContent(html);
              infowindow.open(map,marker1);
           });

     if(openers != ''&&!isEmpty(openers)){
              for(var i in openers){
                var opener = document.getElementById(openers[i]);
                opener.on".$this->window_trigger." = function() {

                 infowindow.close();
                 infowindow.setContent(html);
                 infowindow.open(map,marker1);

               return false;
                };
              }
           }
     ":"")."
           if(sidebar_id != ''){
               var sidebar = document.getElementById(sidebar_id);
      if(sidebar!=null && sidebar!=undefined && title!=null && title!=''){
       var newlink = document.createElement('a');
       ".(($this->info_window)?"
             newlink.onclick=function(){infowindow.open(map,marker1); return false};
       ":"
       newlink.onclick=function(){map.setCenter(point); return false};
       ")."
       newlink.innerHTML = title;
       sidebar.appendChild(newlink);
      }
           }
                }
       return marker1;
   }
     ";
        return $_output;
    }

function addMarkerByAddress($address,$title = '',$html = '',$price='',$tooltip = '', $icon_filename = '', $icon_shadow_filename='') {
        if(($_geocode = $this->getGeocode($address)) === false)
            return false;
        return $this->addMarkerByCoords($_geocode['lon'],$_geocode['lat'],$title,$html,$price,$tooltip, $icon_filename, $icon_shadow_filename);
    }

function addMarkerByCoords($lon,$lat,$title = '',$html = '',$price,$tooltip = '', $icon_filename = '', $icon_shadow_filename='') {
        $_marker['lon'] = $lon;
        $_marker['lat'] = $lat;
        $_marker['html'] = (is_array($html) || strlen($html) > 0) ? $html : $title;
        $_marker['title'] = $title;
        $_marker['tooltip'] = $tooltip;
        $_marker['price'] = (string)$price;

        if($icon_filename!=""){
            $_marker['icon_key'] = $this->setMarkerIconKey($icon_filename, $icon_shadow_filename);
            if($icon_shadow_filename!=""){
               $_marker['shadow_icon']=1;
            }   
        }else if( $this->default_icon != ''){
         $_marker['icon_key'] = $this->setMarkerIconKey($this->default_icon, $this->default_icon_shadow);
         if($this->default_icon_shadow!=""){
            $_marker['shadow_icon']=1;
         }
        }        
        $this->_markers[] = $_marker;
        $this->adjustCenterCoords($_marker['lon'],$_marker['lat']);
        // return index of marker
        return count($this->_markers) - 1;
    }



I know its lots of code here. But all you have to do search the functions and replace the function with the above functions...

Now you have to change few more code which you will call by map object.


 $gmap = new GoogleMap();
 $gmap->addMarkerByCoords($LONGITUDE, $LATITUDE, $title, $html_info_window_data,'your label text');

2 comments:

  1. is there any demo or source code

    ReplyDelete
    Replies
    1. Please take a look at the following URL..

      http://scottie-smith.com/search?proper_types=RES

      I have already share the code with you.

      Delete