Web Tutorial: How to Add Marker in Google Maps Dynamically?

by
how to add marker in google maps?

You may have used Google Maps to look-up for directions towards a place many times in your life, but do you know that you can make your own custom map as well? Yes, you have heard it right. The probabilities of creating a customize map are practically unlimited. You can customize and place a marker on google maps as required. Thus, it’s a good way to quickly set up and explore your favorite areas on a single map.

Based on the resources of information available in the Google Maps API, earlier it was hard to find any details about an extensive feature that is a custom marker on google maps. But nowadays, there is plenty of information available about this feature that would be helpful to a number of designers and web developers.

In this web development tutorial, we will learn how to add marker in google maps dynamically using a custom HTML marker. Before we proceed with the demo, let’s first understand the basics about what actually a custom HTML marker is?

What is a Marker?

A marker is a standard image which describes a place on a map. In google maps, a marker is a type of overlay which shows an icon that identifies the location. Usually, a common google map marker is symbolized by a pin.

Markers are designed in a way that they look interactive. We can show custom images as markers that are referred to as icons. Google Map API allows us to set a custom icon within the marker’s construction. We can also drag, rotate and replace the markers on a map by changing its property.

Now let’s move on the step by step tutorial.

How to Add Marker in Google Maps?

Step 1: Basic Setup

<?php

function cur_location() {

  $labels = array(
    "name" => __( "Places", "text_domain" ),
    "singular_name" => __( "Place", "text_domain" ),
  );

  $demo = array(
    "label" => __( "Places", "text_domain" ),
    "labels" => $labels,
    "description" => "",
    "public" => true,
    "publicly_queryable" => true,
    "show_ui" => true,
    "delete_with_user" => false,
    "show_in_rest" => true,
    "rest_base" => "",
    "rest_controller_class" => "WP_REST_Posts_Controller",
    "has_archive" => false,
    "show_in_menu" => true,
    "show_in_nav_menus" => true,
    "exclude_from_search" => false,
    "capability_type" => "post",
    "map_meta_cap" => true,
    "hierarchical" => false,
    "rewrite" => array( "slug" => "location", "with_front" => true ),
    "query_var" => true,
    "supports" => array( "title" ),
  );

  register_post_type( "location", $demo );
}

add_action( 'init', 'cur_location' );

Step 2: Getting Google Maps API

Go to https://cloud.google.com/maps-platform/

  • Click on “Get Started”
  • Check Maps & Places, and then click “Continue”
  • Create a Project
  • Go to API & Services -> Credentials
  • Click on “Create Credentials” -> API key, and copy the API key.
  • Check API Library and enable the following API
  • Maps JavaScript API
  • Geocoding API
  • Places API
  • Now your Google Maps API key is ready to be used.

Step 3: Setting Google Maps API

function google_init() {
    acf_update_setting('google_api_key', 'your_googlemaps_api_here');
}
add_action('acf/init', google_init);

Step 4: Enqueue Scripts

function googlemaps_scripts() {
  if (!is_admin()) {
    wp_register_script('googlemaps_api', 'https://maps.googleapis.com/maps/api/js?key=your_google_maps_api&callback', array(), '', false);
      wp_enqueue_script('googlemaps_api');
      
      wp_register_script('gmaps-init', get_stylesheet_directory_uri().'/gmaps.js', array(), '', false);
      wp_enqueue_script('gmaps-init');
  } 
}
add_action('wp_enqueue_scripts', 'googlemaps_scripts', 100);

Step 5: Include the given code to the gmaps.js file

(function($) {

/*
*  new_map
*
*  This function will render a Google Map onto the selected jQuery element
*
*  @type  function
*  @date  03/07/2020
*  @since 4.3.0
*
*  @param $el (jQuery element)
*  @return  n/a
*/

function new_map( $el ) {
  
  // var
  var $markers = $el.find('.marker');
  
  
  // vars
  var demo = {
    zoom    : 18,
    center    : new google.maps.LatLng(0, 0),
    mapTypeId : google.maps.MapTypeId.ROADMAP
  };
  
  
  // create map           
  var map = new google.maps.Map( $el[0], demo);
  
  
  // add a markers reference
  map.markers = [];
  
  
  // add markers
  $markers.each(function(){
    
      add_marker( $(this), map );
    
  });
  
  
  // center map
  center_map( map );
  
  
  // return
  return map;
  
}

/*
*  add_marker
*
*  This function will add a marker to the selected Google Map
*
*  @type  function
*  @date  03/07/2020
*  @since 4.3.0
*
*  @param $marker (jQuery element)
*  @param map (Google Map object)
*  @return  n/a
*/

function add_marker( $marker, map ) { 
  // var
  var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );
    var icon = $marker.attr('data-img');
  // create marker
  var marker = new google.maps.Marker({
    position  : latlng,
    map       : map,
    icon      : icon
  });

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

    });
  }

}

/*
*  center_map
*
*  This function will center the map, showing all the markers attached to this map
*
*  @type  function
*  @date  03/07/2020
*  @since 4.3.0
*
*  @param map (Google Map object)
*  @return  n/a
*/

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( 18 );
  }
  else
  {
    // fit to bounds
    map.fitBounds( bounds );
  }

}

/*
*  document ready
*
*  This function will render each map when the document is ready (page has loaded)
*
*  @type  function
*  @date  03/07/2020
*  @since 5.0.0
*
*  @param n/a
*  @return  n/a
*/
// global var
var map = null;

$(document).ready(function(){

  $('.acf-map').each(function(){

    // create map
    map = new_map( $(this) );

  });
 
        //zoom
      google.maps.event.addListener( map, 'zoom_changed', function( e ) {
          
          var zoom = map.getZoom();   
      
             if(zoom!= 5)           
             {
      var bounds = map.getBounds();
      
               myLatLngss = [];
                $.each( map.markers, function( i, marker ){     
      var myLatLng = new google.maps.LatLng(marker.position.lat(), marker.position.lng() ); 
            
      if(bounds.contains(myLatLng)===true) {            
                 myLatLngss.push( myLatLng );
          }
          else {
               
          }
      });
               if(myLatLngss.length > 0)
               { 
                 document.cookie = "coordn="+myLatLngss;
                 $("#customzm").load(location.href + " #customzm");                 
               } 
            } 
             
         });
   google.maps.event.addListener(map, 'dragend', function() {
   //alert('map dragged');
   var bounds = map.getBounds();
      
                  myLatLngss = [];
                $.each( map.markers, function( i, marker ){

      var myLatLng = new google.maps.LatLng(marker.position.lat(), marker.position.lng() ); 
          
      if(bounds.contains(myLatLng)===true) {            
                 myLatLngss.push( myLatLng );
          }
          else {
   
          }
           if(myLatLngss.length > 0)
               {
                 document.cookie = "coordn="+myLatLngss;
                 $("#customzm").load(location.href + " #customzm");                 
               }
      });
   
 } );
        

});

})(jQuery);

Step 6: Create a Shortcode

// Shortcode - [googlemap_locations]

function googlemap_locations (){
    
    $demo = array(
        'post_type' => 'location',
        'posts_per_page' => -1,
    );
    
    $locations_query = new WP_QUERY($demo);
    
    if ( $locations_query->have_posts() ) {
    
    ob_start(); ?>

    <div class="acf-map" style="overflow: hidden; position: relative;">

      <?php while ( $locations_query->have_posts() ) {
        $locations_query->the_post(); 
        $addr = get_field('address');
        $title = get_the_title();
        $outlet_type = get_field('outlet_type');
        $phone = get_field('phone');
                        
            if ($outlet_type == 'regular') {
                $type_icon = get_stylesheet_directory_uri().'/images/green-marker.png';
                $outlet_text = 'Regular Outlet';
            } elseif ($outlet_type == 'special') {
               $type_icon = get_stylesheet_directory_uri().'/images/red-marker.png';
                $outlet_text = 'Special Outlet'; 
            } else {
              $type_icon = get_stylesheet_directory_uri().'/images/gray-marker.png';
              $outlet_text = 'Upcoming Outlet';
            }

        ?>
        
        <div class="marker" data-lat="<?php echo $addr['lat']; ?>" data-lng="<?php echo $addr['lng']; ?>" data-img="<?php echo $type_icon; ?>">
            <div class="inside-marker">
              <h5><?php echo $title; ?></h5>
              <?php
                  echo $outlet_text.'<br>';   
                  if($phone) {
                   echo 'Phone: '.$phone;       
                  }
              ?>
          </div>
        </div>
        
    <?php } ?>
    </div>
    
    <?php wp_reset_postdata(); 
    
    }
    
    return ob_get_clean();
        
}

add_shortcode( 'locations_map', 'locations_map' );

Frequently Asked Questions

1. What is Google Maps?

Google Maps is a web based location service started by Google that provides detailed information about geographical areas across the globe. Google Maps offers different views of the landscape, that includes Street, Traffic, Terrain and Satellite, that can be chosen using some options available within the map.

2. What is a Marker in Google Maps?

A marker on google maps identifies the location. Markers are a type of overlay. Generally, markers are shown using a standard image known as “icons”, which can also be customize as per the requirement.

3. How do I put a marker on Google Maps?

To put a marker on google maps, first you need to open Google maps on your browser. Now you can create a new map or open an existing map. Then click on add marker. After that, you need to select the layer and click on the place where you want to put the marker. Then add a name to that marker. Save it with relevant name. And done.

4. How does Google Maps gather data?

Google Maps is one of the best technology inventions done by Google if we talk about traffic info, route mapping and navigation. The map that you use for location search, is compiled by a private company that has a partnership with Google. Other than that, Google takes help from local guides, satellite views, map markers and more.

Conclusion

Using the above example, we have explained how to add a marker in google map. This is just the basic tutorial of adding a google map marker. However, you can also add animation in this tutorial to make it more interactive. For any trouble or query regarding the example, feel free to reach out to us using the contact form. Our experienced web developers will guide you for the solution accordingly.

You may also like,

Author Bio

Jigar Mistry

Jigar Mistry is the Founder of Monocubed and is the main curator and writer of the content found on this site. He has 14+ years of experience in the information technology industry. He always believes in quality, in terms of code and application.

Sign up for weekly updates from Monocubed.