Support

Account

Home Forums General Issues Adding Polygons to a Google Map

Solving

Adding Polygons to a Google Map

  • I’m trying to make it possible to add polygons to a map in the Google Map field, along with a marker. I found a pen with relatively simple code that shows how to create a polygon tool on a Google Map, but how to integrate it within the existing Google Map field, or an extension of it, is beyond my capabilities.

    Has anyone been able to accomplish something like this? Looking in this forum, I found one related topic, but it’s over 2 years old, and the suggestions in the replies are old, unmaintained plugins that won’t really work (they don’t seem to be using Google Maps).

    This may just be complex, but I’m hoping someone can point me to an existing solution, or at least some steps to get started. Thanks!

  • @updownupdown Hi, once you add code for google maps for acf, you need to input the coordinates of polygon:

    // center map
    	center_map( map );
    
    	// Define the LatLng coordinates for the polygon.
    	var triangleCoords = [
    		{lat: 44.28223, lng: 20.63992},
    		{lat: 44.28253, lng: 20.63935},
    		{lat: 44.28301, lng: 20.63984},
    		{lat: 44.28226, lng: 20.64103},
    		{lat: 44.28246, lng: 20.64138},
    		{lat: 44.28192, lng: 20.64267},
    		{lat: 44.2812, lng: 20.64186},
    		{lat: 44.28206, lng: 20.63973}
    	];
    
    	  // Construct the polygon.
    	  var bermudaTriangle = new google.maps.Polygon({
    	  	paths: triangleCoords,
    	  	strokeColor: '#FF0000',
    	  	strokeOpacity: 0.8,
    	  	strokeWeight: 3,
    	  	fillColor: '#FF0000',
    	  	fillOpacity: 0.35
    	  });
    	  bermudaTriangle.setMap(map);
    
    	  // Add a listener for the click event.
    	  bermudaTriangle.addListener('click', showArrays);
    
    	  infoWindow = new google.maps.InfoWindow;
    // }
    

    after that you can render the polygon with this piece of code:

    /** @this {google.maps.Polygon} */
    function showArrays(event) {
      // Since this polygon has only one path, we can call getPath() to return the
      // MVCArray of LatLngs.
      var vertices = this.getPath();
    
      var contentString = '<b>Bermuda Triangle polygon</b><br>' +
          'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
          '<br>';
    
      // Iterate over the vertices.
      for (var i =0; i < vertices.getLength(); i++) {
        var xy = vertices.getAt(i);
        contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' +
            xy.lng();
      }
    
      // // Replace the info window's content and position.
      // Turned off since i didn't need the rendering of tooltip over polygon.
      // infoWindow.setContent(contentString);
      // infoWindow.setPosition(event.latLng);
    
      // infoWindow.open(map);
    }
    	

    And that is it 🙂

    Here is the code i use for google maps on one of the wp website where i needed polygon area:

    <style type="text/css">
    
    .acf-map {
    	width: 100%;
    	height: 400px;
    	border: #ccc solid 1px;
    	/* margin: 20px 0; */
    }
    
    /* fixes potential theme css conflict */
    .acf-map img {
       max-width: inherit !important;
    }
    
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?key=ADD-YOUR-KEY-HERE"></script>
    <script type="text/javascript">
    (function($) {
    
    /*
    *  new_map
    *
    *  This function will render a Google Map onto the selected jQuery element
    *
    *  @type	function
    *  @date	8/11/2013
    *  @since	4.3.0
    *
    *  @param	$el (jQuery element)
    *  @return	n/a
    */
    
    function new_map( $el ) {
    	
    	// var
    	var $markers = $el.find('.marker');
    	
    	
    	// vars
           //custom styling of the map
    	var args = {
    		zoom		: 16,
    		center		: new google.maps.LatLng(0, 0),
    		
    		styles: [
    				{
    					"featureType": "all",
    					"elementType": "geometry",
    					"stylers": [
    						{
    							"color": "#574029"
    						}
    					]
    				},
    				{
    					"featureType": "all",
    					"elementType": "labels.text.fill",
    					"stylers": [
    						{
    							"gamma": "1.27"
    						},
    						{
    							"lightness": 20
    						},
    						{
    							"color": "#ffffff"
    						}
    					]
    				},
    				{
    					"featureType": "all",
    					"elementType": "labels.text.stroke",
    					"stylers": [
    						{
    							"saturation": "-100"
    						},
    						{
    							"lightness": "-100"
    						},
    						{
    							"weight": "1.19"
    						},
    						{
    							"gamma": "0.00"
    						},
    						{
    							"hue": "#ff0000"
    						},
    						{
    							"invert_lightness": true
    						}
    					]
    				},
    				{
    					"featureType": "all",
    					"elementType": "labels.icon",
    					"stylers": [
    						{
    							"visibility": "off"
    						},
    						{
    							"saturation": "-100"
    						},
    						{
    							"lightness": "-100"
    						},
    						{
    							"gamma": "0.00"
    						},
    						{
    							"weight": "0.01"
    						}
    					]
    				},
    				{
    					"featureType": "landscape",
    					"elementType": "geometry",
    					"stylers": [
    						{
    							"lightness": 30
    						},
    						{
    							"saturation": 30
    						},
    						{
    							"color": "#919d8b"
    						}
    					]
    				},
    				{
    					"featureType": "poi",
    					"elementType": "geometry",
    					"stylers": [
    						{
    							"saturation": 20
    						}
    					]
    				},
    				{
    					"featureType": "poi.park",
    					"elementType": "geometry",
    					"stylers": [
    						{
    							"lightness": 20
    						},
    						{
    							"saturation": -20
    						}
    					]
    				},
    				{
    					"featureType": "road",
    					"elementType": "geometry",
    					"stylers": [
    						{
    							"lightness": "40"
    						},
    						{
    							"saturation": -30
    						}
    					]
    				},
    				{
    					"featureType": "road",
    					"elementType": "geometry.stroke",
    					"stylers": [
    						{
    							"saturation": 25
    						},
    						{
    							"lightness": "100"
    						},
    						{
    							"gamma": "1.00"
    						},
    						{
    							"weight": "0.78"
    						}
    					]
    				},
    				{
    					"featureType": "water",
    					"elementType": "all",
    					"stylers": [
    						{
    							"lightness": -20
    						}
    					]
    				}
    			],
    		mapTypeId	: google.maps.MapTypeId.ROADMAP
    	};
    	
    	
    	// 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 );
    
    	// Define the LatLng coordinates for the polygon.
    	var triangleCoords = [
    		{lat: 44.28223, lng: 20.63992},
    		{lat: 44.28253, lng: 20.63935},
    		{lat: 44.28301, lng: 20.63984},
    		{lat: 44.28226, lng: 20.64103},
    		{lat: 44.28246, lng: 20.64138},
    		{lat: 44.28192, lng: 20.64267},
    		{lat: 44.2812, lng: 20.64186},
    		{lat: 44.28206, lng: 20.63973}
    	];
    
    	  // Construct the polygon.
    	  var bermudaTriangle = new google.maps.Polygon({
    	  	paths: triangleCoords,
    	  	strokeColor: '#FF0000',
    	  	strokeOpacity: 0.8,
    	  	strokeWeight: 3,
    	  	fillColor: '#FF0000',
    	  	fillOpacity: 0.35
    	  });
    	  bermudaTriangle.setMap(map);
    
    	  // Add a listener for the click event.
    	  bermudaTriangle.addListener('click', showArrays);
    
    	  infoWindow = new google.maps.InfoWindow;
    // }
    
    	
    	// return
    	return map;
    	
    }
    
    /*
    *  add_marker
    *
    *  This function will add a marker to the selected Google Map
    *
    *  @type	function
    *  @date	8/11/2013
    *  @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') );
    
    	// create marker
    	icon = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
    	var marker = new google.maps.Marker({
    		position	: latlng,
    		icon        : icon,
    		map			: map
    	});
    
    	// 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 markers attached to this map
    *
    *  @type	function
    *  @date	8/11/2013
    *  @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( 16 );
    	}
    	else
    	{
    		// fit to bounds
    		map.fitBounds( bounds );
    	}
    
    }
    
    /** @this {google.maps.Polygon} */
    
    function showArrays(event) {
      // Since this polygon has only one path, we can call getPath() to return the
      // MVCArray of LatLngs.
      var vertices = this.getPath();
    
      var contentString = '<b>Bermuda Triangle polygon</b><br>' +
          'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
          '<br>';
    
      // Iterate over the vertices.
      for (var i =0; i < vertices.getLength(); i++) {
        var xy = vertices.getAt(i);
        contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' +
            xy.lng();
      }
    
      // // Replace the info window's content and position.
      // Turned off since i didn't need the rendering of tooltip over polygon.
      // infoWindow.setContent(contentString);
      // infoWindow.setPosition(event.latLng);
    
      // infoWindow.open(map);
    }
    
    /*
    *  document ready
    *
    *  This function will render each map when the document is ready (page has loaded)
    *
    *  @type	function
    *  @date	8/11/2013
    *  @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) );
    
    	});
    
    });
    
    })(jQuery);
    </script>

    and i used this polygon render by google as starting point, and of course the pen u mentioned earlier to get the coordinates of the polygon i needed.

  • Thanks for the comprehensive answer DarthTicius. I guess the main thing which was causing my trouble was some way to have a polygon drawing tool in the backend, for non-technical users to add their own polygon shapes along with their marker, within the location field interface. I probably should have been clearer on that, sorry for the confusion!

    I’ve moved on to using another solution for this project, though this may still be something that would be useful at some point. It looks like you’ve definitely provided all the pieces necessary to display the polygons on the front-end though, hopefully that will be useful for several people in the future.

  • Hi @updownupdown,

    I’m trying to do the same. Can you let me know which other solution you’re using?

    Thank you in advance.

  • I ended up using a solution outside ACF altogether, basically embedding an old Google My Maps the client had been using. Not ideal at all.

  • Don’t know if this will help you or not, but I’ve never used the ACF map field for anything but a simple map. For doing complex maps I use this http://www.wpgmaps.com/purchase-professional-version/

  • Hi,

    I’m also very interested by Polygon feature: I would like be able to add Polygons like we can add Markers: to enable my front user to send me this kind of datas.

    I already use WPGMAPSPro but even if it owns many more features (like polygons), it also hundred less flexible than ACF MAP: we can’t use it as field…

    Does someone found a solution?

Viewing 7 posts - 1 through 7 (of 7 total)

The topic ‘Adding Polygons to a Google Map’ is closed to new replies.