apamphilon

Create A Google Map With Custom Marker

In this post I am going to show you how to create a Google Map using the API. The Map will have a custom marker, which will feature an info window on click. You can see the finished map at the bottom of the post.

First of all we will need to link to the API. Add the following code to your footer:

<script src="https://maps.googleapis.com/maps/api/js"></script>

or if you are using WordPress, enqueue the script like so:

function enqueue() {
    wp_enqueue_script('google-maps', 'http://maps.googleapis.com/maps/api/js');
}

add_action( 'wp_enqueue_scripts', 'enqueue' );

The HTML:

<!-- google font -->
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300,400,700' rel='stylesheet' type='text/css'>

<!-- google map api -->
<script src="https://maps.googleapis.com/maps/api/js"></script>

<h1>Google Maps Custom Marker Demo</h1>

<!-- START MAP -->  
<div id="google-map">

    <div class="marker" data-lat="53.483144" data-lng="-2.233307">

        <span class="marker-title">
            <strong>The Arndale</strong>
        </span>

        <span>Market Street <br>Manchester <br> M4 3AQ</span>

    </div>  

    <div class="marker" data-lat="53.4842467" data-lng="-2.2432947">

        <span class="marker-title">
            <strong>intu Trafford Centre</strong>
        </span>

        <span>Manchester <br> M17 8AA</span>

    </div>

</div>
<!-- END MAP -->

The CSS

//page styles
body {
    margin: 0 50px 50px;    
    font-family: 'Open Sans', sans-serif;
}

h1 {
    font-size: 40px;
    padding: 50px 0;
    text-align: center;
    font-weight: 700;
}

//map starts here
#google-map {
    height: 400px;
    width: 90%;
    margin: 0 auto;
}

.marker {
    display: none;
}

span {
    line-height: 1.5;
}

.marker-title {
    display: block;
    font-family: Arial, Helvetica, sans-serif;
    font-weight: bold;
    color: #58595B;
    margin-bottom: 2px;
}

The javaScript

//google map
    //This function will render a Google Map onto the selected jQuery element
    function render_map( $el ) {

        // var
        var $markers = $el.find('.marker');

        // vars
        var args = {
            //overlay
            scrollwheel : false,
            zoomControl : true,
            streetViewControl: false,
            mapTypeControl: true,
            panControl: false,
            //options
            scrollwheel : false,
            zoom        : 16,
            center      : new google.maps.LatLng(0, 0),
            mapTypeId   : google.maps.MapTypeId.ROADMAP,
            //optionsal styles
            styles: [
                {
                    featureType: 'all',
                    stylers: [
                        { saturation: -100 }
                    ]
                }
            ]
        };

        // create map               
        var map = new google.maps.Map( $el[0], args);

        // add a markers reference
        map.markers = [];

        // add markers
        $markers.each(function(){

            add_marker( $(this), map );

        });

        // center map
        center_map( map );

    }

    //add_marker 
    //This function will add a marker to the selected Google Map

    var currentInfoWindow;

    function add_marker( $marker, map ) {

        // var
        var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );

        //custom img
        var image = 'http://www.tnetnoc.com/public/ANS/Dynaflex/Images/HCL/SEO/St-Kilda-Guide/Icons/MarkerPurple.png'

        // create marker
        var marker = new google.maps.Marker({
            position    : latlng,
            map         : map,
            icon        : image
        });

        // add to array
        map.markers.push( marker );

        // if marker contains HTML, add it to an infoWindow
        if( $marker.html() )
        {
            // create info window
            var infowindow = new google.maps.InfoWindow({
                content     : $marker.html()
            });

            // show info window when marker is clicked   
            google.maps.event.addListener(marker, 'click', function() {

                infowindow.open(map, marker);

                //close all other infowindows
                if (currentInfoWindow && currentInfoWindow != infowindow) {
                    currentInfoWindow.close();
                }

                currentInfoWindow = infowindow;
            });

            // close info window when map is clicked
            google.maps.event.addListener(map, 'click', function(event) {
                if (currentInfoWindow) {
                    currentInfoWindow.close();
                }
            });
        }

    }

    //center_map
    //This function will center the map, showing all markers attached to this map

    function center_map( map ) {

        // vars
        var bounds = new google.maps.LatLngBounds();

        // loop through all markers and create bounds
        $.each( map.markers, function( i, marker ){

            var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );

            bounds.extend( latlng );

        });

        // only 1 marker?
        if( map.markers.length == 1 )
        {
            // set center of map
            map.setCenter( bounds.getCenter() );
            map.setZoom( 16 );
        }
        else
        {
            // fit to bounds
            map.fitBounds( bounds );
        }

    }

    //document ready
    //This function will render each map when the document is ready (page has loaded)
    $(document).ready(function(){
        $('#google-map').each(function(){
            render_map( $(this) );
        });
    });

    //if in tabs / accordion (hidden)
//  $(document).ready(function(){
//      $('.google-map').each(function(){
//          var map = $(this);

//          if ($(this).parents('.map').length) {
//              $(this).parents('.map').children('.btn').on('click', function() {
//                  if (!map.hasClass('rendered')) {
//                      render_map(map);
//                      map.addClass('rendered');
//                  }
//              });
//          } else {
//              render_map(map);
//          }
//      });
//  });

See the Pen Google Maps by Alex Pamphilon (@apamphilon) on CodePen.


Comments: