Yii 1.1: egmap

Objet-oriented PHP abstraction to the Google Maps API to ease the process of adding a Google Map on your Yii projects.


Nearly totally re-written, this extension is the new version of EGMap. I decided to include it as a new version as this one breaks backwards compatibility. I did that in order to implement a different approach, more like the Yii style.

With the new code it was also possible to do lot of code cleansing, making the classes more compact.

Now, magic getters and setters allows the use of options and functions pre-named as set or get, like properties, more or less what is happening with CComponent.

This version have (including all of the previous EGMap library):


Note: Information about previous versions of this extension are on this Forum Post

EGMap Google Maps Extension for Yii
IMPORTANT NOTICE The repository location has now changed to a better github location, so people can easily work on that extension only.

Change Log

  • 19-12-2011 Added EGMapPolylineEncoder to encode polygon paths and Elevation API v3 support
  • 19-12-2011 Update geolocation from V2 to V3 API by Matt Cheale
  • 19-12-2011 Fixed reverse geocoding info bug
  • 17-12-2011 Fixed a minor and silly bug
  • 17-12-2011 Added Polygons [by Matt Kay], Rectangles and Circles support
  • 16-12-2011 Fixed CURL open_basedir restriction and added marker animations
  • 23-11-2011 Fixed IE 8 loading bug (thanks ghadad)
  • 12-10-2011 Code improvements: Added support for InfoBox, included a Reverse Geolocation class tool with options to update form fields on center change.
  • 23-03-2011 Updated Reverse GeoCoding from v2 to v3 (check Google Code SVN Repository)
  • 20-03-2011 Included support for Polygons (check Google Code SVN Repository)
  • 11-02-2011 Included support for language and region maps
  • 11-02-2011 Included support for addDOMEventListenerOnce and addEventListenerOnce (thanks Johnatan)
  • 03-02-2011 Fixed small bug on registerPlugin Function (thanks Rangel Reale)


Unpack the contents of the zip file and place it on your protected/extensions folder. This package names EGMap library folder EGMAP, so make sure you read http://www.yiiframework.com/doc/api/1.1/YiiBase#import-detail, to understand clearly how to setup correctly the folder's extension.

Markers and Markers with Labels

The following example shows you how you can use markers and markers with labels. It also shows how to enable a default marker clusterer

// ext is your protected.extensions folder
// gmaps means the subfolder name under your protected.extensions folder
$gMap = new EGMap();
$gMap->zoom = 10;
$mapTypeControlOptions = array(
  'position'=> EGMapControlPosition::LEFT_BOTTOM,
$gMap->mapTypeControlOptions= $mapTypeControlOptions;
$gMap->setCenter(39.721089311812094, 2.91165944519042);
// Create GMapInfoWindows
$info_window_a = new EGMapInfoWindow('<div>I am a marker with custom image!</div>');
$info_window_b = new EGMapInfoWindow('Hey! I am a marker with label!');
$icon = new EGMapMarkerImage("http://google-maps-icons.googlecode.com/files/gazstation.png");
$icon->setSize(32, 37);
$icon->setAnchor(16, 16.5);
$icon->setOrigin(0, 0);
// Create marker
$marker = new EGMapMarker(39.721089311812094, 2.91165944519042, array('title' => 'Marker With Custom Image','icon'=>$icon));
// Create marker with label
$marker = new EGMapMarkerWithLabel(39.821089311812094, 2.90165944519042, array('title' => 'Marker With Label'));
$label_options = array(
// Two ways of setting options
$marker_options = array(
  // check the style ID 
  // afterwards!!!
  'labelAnchor'=>new EGMapPoint(22,2),
$marker->labelContent= '$425K';
$marker->raiseOnDrag= true;
$marker->setLabelAnchor(new EGMapPoint(22,0));
// enabling marker clusterer just for fun
// to view it zoom-out the map
$gMap->enableMarkerClusterer(new EGMapMarkerClusterer());
<style type="text/css">
.labels {
   color: red;
   background-color: white;
   font-family: "Lucida Grande", "Arial", sans-serif;
   font-size: 10px;
   font-weight: bold;
   text-align: center;
   width: 40px;     
   border: 2px solid black;
   white-space: nowrap;

KML Service

As KML is a service that is readed from Google services, you cannot use localhost KML files, to do so, you need to specify that is localhost kml file on enableKMLService function and the geoxml3.js plugin should be automatically registered.

$gMap = new EGMap();
// using the new magic setters
// check available options per class
// objects with setMethod,getMethod and
// options array can be set now this way
$gMap->zoom = 10;
$mapTypeControlOptions = array(
   // yes we can position the controls now
   // where we want
   'position'=> EGMapControlPosition::LEFT_BOTTOM,
$gMap->mapTypeControlOptions= $mapTypeControlOptions;
// enabling KML Service. Second parameter of this 
// function tells whether is localhost or not. GeoXML3.js 
// is needed to read localhost KML files.

Directions Example

How to work with directions and waypoints

$gMap = new EGMap();
// it can also be called $gMap->height = 400;
$gMap->zoom = 8; 
// set center to inca
$gMap->setCenter(39.719588117933185, 2.9087440013885635);
// my house when i was a kid
$home = new EGMapCoord(39.720991014764536, 2.911801719665541);
// my ex-school
$school = new EGMapCoord(39.719456079114956, 2.8979293346405166);
// some stops on the way
$santo_domingo = new EGMapCoord(39.72118906848983, 2.907628202438368);
$plaza_toros  = new EGMapCoord(39.71945607911511, 2.9049245357513565);
$paso_del_tren = new EGMapCoord( 39.718762871171776, 2.903637075424208 );
// Waypoint samples
$waypoints = array(
      new EGMapDirectionWayPoint($santo_domingo),
      new EGMapDirectionWayPoint($plaza_toros, false),
      new EGMapDirectionWayPoint($paso_del_tren, false)
// Initialize GMapDirection
$direction = new EGMapDirection($home, $school, 'direction_sample', array('waypoints' => $waypoints));
$direction->optimizeWaypoints = true;
$direction->provideRouteAlternatives = true;
$renderer = new EGMapDirectionRenderer();
$renderer->draggable = true;
$renderer->panel = "direction_pane";
<div id="direction_pane"></div>

KeyDragZoom Example

How to make use of the KeyDragZoom plugin. When you use the following example, check the small magnifying glass under the zoom control or press the Shift Key to enable the Key Drag Zoom.

$gMap = new EGMap();
$gMap->zoom = 8;
// set center to inca
$gMap->setCenter(39.719588117933185, 2.9087440013885635); 
$gMap->width = 400;
$gMap->height = 400;
// Enable Key Drag Zoom
$zoom_options = array(
   'border'=>'4px dashed black', // strings with double quoted inside!
$drag_Zoom = new EGMapKeyDragZoom($zoom_options);

A More Advanced Example

Where $map is model of database table to save coordinates of a marker point. Example provided by Johnatan

$gMap = new EGMap();
$gMap->zoom = 6;
$mapTypeControlOptions = array(
  'position' => EGMapControlPosition::RIGHT_TOP,
$gMap->mapTypeId = EGMap::TYPE_ROADMAP;
$gMap->mapTypeControlOptions = $mapTypeControlOptions;
// Preparing InfoWindow with information about our marker.
$info_window_a = new EGMapInfoWindow("<div class='gmaps-label' style='color: #000;'>Hi! I'm your marker!</div>");
// Setting up an icon for marker.
$icon = new EGMapMarkerImage("http://google-maps-icons.googlecode.com/files/car.png");
$icon->setSize(32, 37);
$icon->setAnchor(16, 16.5);
$icon->setOrigin(0, 0);
// Saving coordinates after user dragged our marker.
$dragevent = new EGMapEvent('dragend', "function (event) { $.ajax({
                                            'data':({'lat': event.latLng.lat(), 'lng': event.latLng.lng()}),
                                        });}", false, EGMapEvent::TYPE_EVENT_DEFAULT);
// If we have already created marker - show it
if ($map) {
    $marker = new EGMapMarker($map->lat, $map->lng, array('title' => Yii::t('catalog', $items->type->name),
            'icon'=>$icon, 'draggable'=>true), 'marker', array('dragevent'=>$dragevent));
    $gMap->setCenter($map->lat, $map->lng);
    $gMap->zoom = 16;
// If we don't have marker in database - make sure user can create one
} else {
    $gMap->setCenter(38.348850, -0.477551);
    // Setting up new event for user click on map, so marker will be created on place and respectful event added.
    $gMap->addEvent(new EGMapEvent('click',
            'function (event) {var marker = new google.maps.Marker({position: event.latLng, map: '.$gMap->getJsName().
            ', draggable: true, icon: '.$icon->toJs().'}); '.$gMap->getJsName().
            '.setCenter(event.latLng); var dragevent = '.$dragevent->toJs('marker').
            '; $.ajax({'.
              '"data":({"lat": event.latLng.lat(), "lng": event.latLng.lng()}),'.
            '}); }', false, EGMapEvent::TYPE_EVENT_DEFAULT_ONCE));
$gMap->renderMap(array(), Yii::app()->language);

InfoBox Example

InfoBox is a cool plugin that allows you to modify the info windows of your map.

$gMap = new EGMap();
$gMap->width = '100%';
$gMap->height = 300;
$gMap->zoom = 8;
$gMap->setCenter(39.737827146489174, 3.2830574338912477);
$info_box = new EGMapInfoBox('<div style="color:#fff;border: 1px solid black; margin-top: 8px; background: #000; padding: 5px;">I am a marker with info box!</div>');
// set the properties
$info_box->pixelOffset = new EGMapSize('0','-140');
$info_box->maxWidth = 0;
$info_box->boxStyle = array(
    'background'=>'"url(http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.9/examples/tipbox.gif) no-repeat"'
$info_box->closeBoxMargin = '"10px 2px 2px 2px"';
$info_box->infoBoxClearance = new EGMapSize(1,1);
$info_box->enableEventPropagation ='"floatPane"';
// with the second info box, we don't need to 
// set its properties as we are sharing a global 
// info_box
$info_box2 = new EGMapInfoBox('<div style="color:#000;border: 1px solid #c0c0c0; margin-top: 8px; background: #c0c0c0; padding: 5px;">I am a marker with info box 2!</div>');
// Create marker
$marker = new EGMapMarker(39.721089311812094, 2.91165944519042, array('title' => 'Marker With Info Box'));
// add two 
$marker2 = new EGMapMarker(39.721089311812094, 2.81165944519042, array('title' => 'Marker With Info Box 2'));

Rectangle Example [New]

$gMap = new EGMap();
$gMap->width = '100%';
$gMap->height = 300;
$gMap->zoom = 4;
$gMap->setCenter(25.774252, -80.190262);
$bounds = new EGMapBounds(new EGMapCoord(25.774252, -80.190262),new EGMapCoord(32.321384, -64.75737) );
$rec = new EGMapRectangle($bounds);
$rec->addHtmlInfoWindow(new EGMapInfoWindow('Hey! I am a rectangle!'));

Circle Example [New]

$gMap = new EGMap();
$gMap->width = '100%';
$gMap->height = 300;
$gMap->zoom = 4;
$gMap->setCenter(34.04924594193164, -118.24104309082031);
$circle = new EGMapCircle(new EGMapCoord(34.04924594193164, -118.24104309082031));
$circle->radius = 300000;
$circle->addHtmlInfoWindow(new EGMapInfoWindow('Hey! I am a circle!'));

Polygon Example [New]

$gMap = new EGMap();
$gMap->width = '100%';
$gMap->height = 300;
$gMap->zoom = 4;
$gMap->setCenter(25.774252, -80.190262);
$coords = array(
       new EGMapCoord(25.774252, -80.190262),
       new EGMapCoord(18.466465, -66.118292),
       new EGMapCoord(32.321384, -64.75737),
       new EGMapCoord(25.774252, -80.190262)
$polygon = new EGMapPolygon($coords);
$polygon->addHtmlInfoWindow(new EGMapInfoWindow('Hey! I am a polygon!'));

Reverse Geocode Example [New]

$gMap = new EGMap();
$gMap->zoom = 5;
$sample_address = 'Czech Republic, Prague, Olivova';
// Create geocoded address
$geocoded_address = new EGMapGeocodedAddress($sample_address);
// Center the map on geocoded address
 $gMap->setCenter($geocoded_address->getLat(), $geocoded_address->getLng());
// Add marker on geocoded address
     new EGMapMarker($geocoded_address->getLat(), $geocoded_address->getLng())

Elevation Example [New]

$e = new EGMapElevationInfo(
     array('25.774252, -80.190262',
           '18.466465, -66.118292',
            new EGMapCoord(32.321384, -64.75737), /* we can also use EGMapCoord */
            new EGMapCoord(25.774252, -80.190262)));
$e->elevationRequestJson(new EGMapClient());
$loc =  $e->getLocations();
foreach($loc as $l)
    echo $l->lat.'<br/>';
    echo $l->lng.'<br/>';
    echo $l->resolution.'<br/>';
    echo $l->elevation.'<br/>';
    echo '--------------<br/>';


Be up-to-date with this extension on my blog. I will write demos and explain its total functionality there in order not to make this article too long.

I love what I do, if you appreciate my work I accept donations at Gittip


web development has never been so fun

Total 20 comments

#20009 report it
gopi_patel at 2017/01/06 02:22am
how to set setApikey in Egmap

How can set api key for localhost and Production ? below is my code.I tried using gMap->setAPIKey('dev.localo.com',MYAPIKEY)..but not working ..

$gMap = new EGMap();
$gMap->zoom = 16;
$gMap->mapTypeControl = false;
$gMap->scrollwheel = false;
$gMap->setContainerStyle('width', '100%');
$gMap->setContainerStyle('height', '250px');
$gMap->setCenter($defaultVenue->lat, $defaultVenue->lng);
// Create GMapInfoWindows
$infoWindow = new EGMapInfoWindow('<div>' . nl2br($defaultVenue->full_address) . '</div>');
// Create marker
$marker = new EGMapMarker($defaultVenue->lat, $defaultVenue->lng, ['title' => $defaultVenue->full_address]);
#19117 report it
Dhara at 2015/03/21 01:48am
Map not showing in clistview with pagination


Nice extension.

I have used it in CListview.In which each record has location. In First page, all record properly display Map. But when i click on second page,Map doesn't show. It only bind div with Id 'EGMapContainer12' etc... Other data not binded in this div.

Any Solution?

#18488 report it
swafsarl at 2014/11/05 08:02pm
need to use the fitbounds

hello guys, i need to use the fitbounds function plz see this script http://www.weboblog.fr/zoom-automatique-fitbounds-v3 is this possible with ur extension or should i implement my own javascript.


for(var i = 0; i < myPoints.length; i++)
{ bounds.extend(myPoints[i]); var thisMarker = addThisMarker(myPoints[i],i); thisMarker.setMap(map); } /* Ici, on ajuste le zoom de la map en fonction des limites */ map.fitBounds(bounds);
#18331 report it
Antonio Ramirez at 2014/10/16 02:15pm

Yes, you will have to use the GPS of the device to get the lat, lng... the rest is the same.

I highly recommend you to check LeafLetJs for mobile.

#18193 report it
swafsarl at 2014/09/24 01:06pm
html5 self-location

Hello Is there a way to get user own location on mobile device website using this extension? Keep up the good work cheers

#18191 report it
Antonio Ramirez at 2014/09/24 06:59am

Did you get your API key?

#18190 report it
Antonio Ramirez at 2014/09/24 06:58am

Prueba canvas2html o utiliza el método estático de Google para tener una imagen de tu mapa e insertalo en un pdf u otras librerias.

Try canvas2html o use the static method of Google to get an image of the map and insert it into a pdf by using ePdf or other libraries around.

#17603 report it
carpin at 2014/07/07 02:51pm
exportar a pdf

buenas tardes! quiero saber si se puede exportar a pdf el mapa, o si alguien sabe como hacerlo, desde ya muchas gracas!

#16874 report it
skworden at 2014/04/05 11:16pm
Not showing on live server?

It is working fine on localhost but when it's live it doesn't show anything. it only shows the map div and EGMapContainer1 nothing else. Anyone know of a resolution?

                // Create GMapInfoWindows
                $iconimg = Yii::app()->theme->baseUrl.'/assets/img/mapicon.png';
                $icon = new EGMapMarkerImage($iconimg);
                $icon->setSize(32, 37);
                $icon->setAnchor(16, 16.5);
                $icon->setOrigin(0, 0);
                $gMap = new EGMap();
                $gMap->zoom = 14;
                $info_box = new EGMapInfoBox('<div style="color:#000;border: 1px solid black; font-size: 16px; line-height: 16px; text-align:center; background: #f8f8f8; margin-top: 5px; padding: 5px;">
                <img src="'.Yii::app()->theme->baseUrl.'/assets/img/logo.png'.'"></img><br>'.Yii::app()->params['address'].', <br>'.
                Yii::app()->params['city'].', '.Yii::app()->params['state'].' '.Yii::app()->params['zip'].'</div>');
                $info_box->pixelOffset = new EGMapSize('-120','-120');
                $info_box->maxWidth = 0;
                $info_box->boxStyle = array(
                $info_box->closeBoxMargin = '"10px 4px 4px 4px"';
                $info_box->infoBoxClearance = new EGMapSize(1,1);
                $info_box->enableEventPropagation ='"floatPane"';
                $listing_address = Yii::app()->params['address'].', '.
                        Yii::app()->params['city'].', '.Yii::app()->params['state'].' '.Yii::app()->params['zip'];
                // Create geocoded address
                $geocoded_address = new EGMapGeocodedAddress($listing_address);
                // Center the map on geocoded address
                 $gMap->setCenter($geocoded_address->getLat(), $geocoded_address->getLng());
                // Add marker on geocoded address
                $marker = new EGMapMarker($geocoded_address->getLat(), $geocoded_address->getLng(), array('title' =>Yii::app()->params['company'].' - '.Yii::app()->params['tagline'], 'icon'=>$icon));
#16702 report it
Simbioziz at 2014/03/21 04:01am
Problem with map

Iam add post in forum. Please Problems With Route Directions Egmap...

#16698 report it
Antonio Ramirez at 2014/03/20 02:13pm

I dont really understand your issue. Do you guys mind to use the forum to show your issues (with code included) and send the link on my Forum's profile?


#16697 report it
Simbioziz at 2014/03/20 01:21pm
Why a just 10 point i can add on map directions

A problem. I can add to the map just 10 points. If i add more than 10 points of the card simply does not appear in the browser. Gray box. How to overcome this limitation? Thank you.

#16320 report it
Ivanda Nothabeer at 2014/02/10 07:33am
Drawing Straight Lines

I'm trying to figure out how to draw straight lines between co-ordinates but cant seem to get anywhere.

Any hints or examples on how to draw polylines would be really helpful.

#16208 report it
SimonZ at 2014/01/28 03:30pm
Problem left-side control

Add this in CSS where .gmap is the class of the map div

.gmap img{
max-width:none !important;
.gmap label {
  width: auto; display:inline;
#16176 report it
Trejder at 2014/01/26 11:45am
@Victor Silver

egmap is no longer supported, AFAIK. So, you would have to do fork and introduce these changes yourself, in your own version.

#16175 report it
Victor Silver at 2014/01/26 08:30am
Customizing map loading process

How about enabling some customization on how and what triggers the map to be rendered In class EGMap line 545 we see the render triggering process.

google.maps.event.addDomListener(window, "load",' . PHP_EOL . $this->_containerId . '_init);' . PHP_EOL;

What if the DOM object (in this case window) and the event (load) could be overriden ?

#16026 report it
Trejder at 2014/01/11 08:58am

Would you consider to share your solution as either separate or updated extension?

#16024 report it
dacoder at 2014/01/10 08:22pm
plugin updated with ajax render functionality

I have almost completed updating the plugin with some new features and a custom function to render markers dynamically with ajax on window, drag or zoom. Contact me at ron1703@gmail.com incase anyone needs help or code snippets concerning the same.

#16020 report it
dacoder at 2014/01/10 03:23am

It is the former, manipulating ajax on the server would be a silly think to do obviously.
- Now coming to the point, I have built a large part of the map display around this extension and since a new feature requires me having to detect bounds within the users window width and update markers on pad/drag/zoom, I realize I will have to bring new events into the picture and change a few functions. Now since all the javascript strings are autogenerated basis our php arrays I would prefer either taking out all the javascript from the extension files and define it manually or update the extension which might be a risky proposition.
- Besides updating content with ajax has a drawback as if you watch the plugin initialization, all lot variables are defined in global scope which makes defining custom functions an absolute chore unless I make them global from the extension files.
This will also create problems doing a render on just the markers and infowindows due to scope issues.
Might redo this extension, giving it a few hours for the answers to roll in.
Added Going through the updated features on maps api and from what I see in the extension, it surely can do with an update right now, many key events are missing.

#16018 report it
Yiimaps at 2014/01/10 02:18am
I am here to help if needed.

contact me on eruaan@gmail.com

Leave a comment

Please to leave your comment.

Create extension