Tag Archives: google maps

How to create a basic Google Maps plugin for WordPress

There might be some WordPress plugins out there that could be used to add Google map to posts and pages. Still I didn’t find it necessary to install one when creating it is fun and easy.

Adding the final plugin to a post/page will be done using shortcode.

First of all you must create the plugin directory in wp-content/plugins/plugin_name.

Add two files here, the first an empty index.php and the second plugin_name.php

In order to be able to activate this plugin some basic details need to be added at the beginning:

/**
 * Plugin Name: Custom Google Maps
 * Plugin URI: http://catalinmunteanu.com
 * Description: Create Google Map element using a location query
 * Version: 1.0.0
 * Author: Catalin Munteanu
 * Author URI: http://catalinmunteanu.com
 */

Then we must create a function that will process this plugin’s shortcode:

 

function google_map_print($attrs, $content=null) {
    $item = shortcode_atts(
        array(
            'location' => null
        ),
        $attrs,
        'google-map'
    );

    $result = '<div>';
        $result .= '<iframe
            width="100%"
            height="250"
            scrolling="no" marginheight="0" marginwidth="0"
            frameborder="0" style="border:0"
            src="https://maps.google.com/maps?f=q&hl=en&geocode=&q='.$item['location'].'&aq=t&ie=UTF8&hq=&t=m&z=17&output=embed">
            </iframe>';
    $result .= '</div>';
    return $result;

}

add_shortcode('google-map', 'google_map_print');

 

That’s all. After you activate the plugin you can add it in your posts and pages using the shortcode:

[google-map location="Bucharest"]

Result:

Google Maps JavaScript Wrapper

Some of the projects I’ve implemented required some dynamic or static maps.

Of course most powerful maps library at that time was Google Maps.

The wrapper allows the insertion of markers with custom icon, circles, polylines and setting the center and zoom of the map.

Here’s one version of the JavaScript Google Maps Wrapper that I’ve created:

function GMaps(opt) {
    this.map          = null;

    this.circles      = [];
    this.markers      = [];
    this.polylines    = [];

    this.m_icon_path  = opt.icon_path || null;
    this.m_icon       = null;
    
    this.lat          = opt.lat || 45.8805435;
    this.lng          = opt.lng || 24.9582169;
    this.zoom         = opt.zoom || 7;

    this._init(opt);
}

GMaps.prototype._init = function(opt) { 
    var self = this;

    if(opt == null) {
        opt = {};
    }

    var map_options = {
        zoom:               self.zoom,
        center:             new google.maps.LatLng(self.lat, self.lng),
        mapTypeId:          google.maps.MapTypeId.ROADMAP,
        streetViewControl:  false,
        scaleControl:       false,
        mapTypeControl:     false,
        panControl:         false,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL
        }
    };

    self.map = new google.maps.Map(document.getElementById(opt.element), map_options);

    if(self.icon_path) {
        self.icon = new google.maps.MarkerImage(self.icon_path, null, null, null, new google.maps.Size(20, 26));
    }
};

GMaps.prototype.check_resize = function() {
    var self = this; 
    
    google.maps.event.addListenerOnce(self.map, 'idle', function() {
        google.maps.event.trigger(self.map, 'resize');
        self.map.setCenter(new google.maps.LatLng(self.lat, self.lng));
    });
};

GMaps.prototype.clear_markers = function() {
    for(var i=0; i<this.markers.length; ++i) {
        if(this.markers[i].circle != null) {
            this.markers[i].circle.setMap(null);
        }

        this.markers[i].setMap(null);
    }

    this.markers = [];
};

GMaps.prototype.clear_polylines = function() {
    for(var i=0; i<this.polylines.length; ++i) {
        if(this.polylines.markers != null) {
            for(var y=0; y<this.polylines.markers.length; ++y) {
                this.polylines.markers[y].setMap(null);
            }
        }

        this.polylines[i].setMap(null);
    }

    this.polylines = [];
};

GMaps.prototype.clear_circles = function() {
    for(var i=0; i<this.circles.length; ++i) {
        this.circles[i].setMap(null);
    }

    this.circles = [];
};

GMaps.prototype.reset = function() {
    this.clear_markers();
    this.clear_polylines();
    this.clear_circles();
};

GMaps.prototype.set_icon_path = function(path) {
    this.icon_path = path;

    if(this.icon_path) {
        this.icon = new google.maps.MarkerImage(this.icon_path, null, null, null, new google.maps.Size(71, 71));
    }
};

GMaps.prototype.set_zoom = function(zoom) {
    this.map.setZoom(zoom);
};

GMaps.prototype.set_center = function(lat, lng, opt) {
    this.map.setCenter(new google.maps.LatLng(lat, lng));

    if(opt && opt.zoom) {
        this.map.setZoom(opt.zoom);
    }
};

GMaps.prototype.add_marker = function(lat, lng, opt) {
    if(opt == null) {
        opt = {};
    }

    var m = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        map:      this.map,
        title:    opt.title
    });

    if(this.icon) {
        m.setIcon(this.icon);
    }

    if(opt.circle) {
        m.circle = new google.maps.Circle({
            center:       new google.maps.LatLng(lat, lng),
            map:          this.map,
            strokeWeight: 0,
            fillColor:    opt.circle_fill || '#F00',
            radius:       opt.circle_radius || 50
        });
    }

    this.markers.push(m);
};

GMaps.prototype.add_polyline = function(items, show_origin) {
    var path = [];

    for(var i=0; i<items.length; ++i) {
        path.push(new google.maps.LatLng(items[i].lat, items[i].lng));
    }

    var p = new google.maps.Polyline({
        path: path,
        map:  this.map
    });
    
    if(show_origin) {
        p.markers = [];
        p.markers.push(this.add_marker(path[0].lat(), path[0].lng(), {}));
        p.markers.push(this.add_marker(path[path.length-1].lat(), path[path.length-1].lng(), {}));
    }

    this.polylines.push(p);
};

GMaps.prototype.add_circle = function(lat, lng, opt) {
    if(opt == null) {
        opt = {};
    }

    this.circles.push(new google.maps.Circle({
        center:       new google.maps.LatLng(lat, lng),
        map:          this.map,
        strokeWeight: 0,
        fillColor:    opt.fill || '#F00',
        radius:       opt.radius || 50
    }));
};

Usage:

Create element:

<div id="map-wrapper"></div>

Set element style:

<style type="text/css">
    #map-wrapper {
        width: 100%;
        height: 100%;
    }
</style>

Create instance of Google Maps Wrapper:

var map_instance = new GMaps({
    element:    'map-wrapper',
    zoom:       7,
    lat:        45.8805435,
    lng:        24.9582169,
    icon_path:  'http://www.catalinmunteanu.com/wp-content/uploads/2015/01/gmaps_marker.png'
});

// Setting map center
map_instance.set_center(45.8805435, 24.9582169, {zoom: 7});

// Setting map zoom
map_instance.set_zoom(7);

// Change/Set marker icon path (or use default icon)
map_instance.set_icon_path('http://www.catalinmunteanu.com/wp-content/uploads/2015/01/GMaps_marker.png');

// Create marker (circle is optional)
map_instance.add_marker(45.8805435, 24.9582169, {
    circle:         true,
    circle_radius:  20000
});

// Create polyline
map_instance.add_polyline([
    {lat: 45.6725422, lng: 23.567376},
    {lat: 45.0239766, lng: 24.887982},
    {lat: 45.6725422, lng: 26.2150817}
], true);

// Create circle
map_instance.add_circle(46.5037588, 24.2036717, {radius: 20000, fill: '#336699'});
map_instance.add_circle(46.5037588, 25.6674779, {radius: 20000, fill: '#336699'});

// To clear the map use
// map_instance.clear_markers();
// map_instance.clear_polylines();
// map_instance.clear_circles();

// Or with just one call
// map_instance.reset();

 

If  you like this article don’t forget to share it.

Load Google Maps Library on the fly

Define the service:

'use strict';

angular
.module('APP.services')
.factory('GMAPS', ['$window', function($window) {
    var self        = this,
        callback    = null;

    $window.gmaps_loaded = function() {
        if(callback) {
            callback();
        }
    };

    self.load = function(cb) {
        if($window.google) {
            cb();
            return;
        }

        callback = cb;

        var gmaps_script = $window.document.createElement('script');

        gmaps_script.type = 'text/javascript';
        gmaps_script.src  = 'https://maps.googleapis.com/maps/api/js?v=3.exp&callback=gmaps_loaded&client=your_client_id';
        $window.document.body.appendChild(gmaps_script);
    };

    return {
        'load': self.load
    };
}])

;

Usage:

'use strict';

angular
.module('APP.home', ['APP.services'])
.controller('TestController', ['GMAPS', function(GMAPS) {

    // Load Google library and initiate it
    GMAPS.load(function() {
        var map = new google.maps.Map(element_id, options);
    });

}])

;