Google Maps with a Simple Marker & Address Geocoding

Published

October 27, 2014

Category

Development

Embedding Google Maps via iFrame is pretty simple. You search for an address on maps.google.com and then get the iFrame-Code to add it to your site. Unfortunately there is no possibility to personalise the map or to hand over the location values dynamically as an address. If you want to have more freedom in terms of appearance and using the same code for different pages with different locations you have to use some JavaScript and the Google Maps API to render the map.

HTML

The map is rendered inside <div id=”map” class=”map”></div>.

<div id="map"class="map"></div>

JavaScript

The Google Script has to be implemented before the render function is defined.

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

The JavaScript below renders the map based on the values “street”, “postal-code”, and “city”. You can hand over more detailed address-values like “state” or “country” in the same way. We were using Advanced Custom Fields to generate the required fields in WordPress and to hand them over in the front-end.

The variable “zoom” defines the start zoom of the map, “mapTypeID” the style and “image” is the custom map-pin. You can personalise your map even more by having a look into the official documentation of Google.

<script type="text/javascript">
    var geocoder;
      var map;
      function initialize() {
    	geocoder = new google.maps.Geocoder();
    	var latlng = new google.maps.LatLng(48.291876,16.339551);
    	var mapOptions = {
    	  zoom: 16,
    	  center: latlng,
    	  mapTypeId: google.maps.MapTypeId.ROADMAP
    	}
    	map = new google.maps.Map(document.getElementById('map'), mapOptions);
    	codeAddress()
      }

      function codeAddress() {
        var image = 'URL TO YOUR CUSTOM PIN';
    	var address = '<?php the_field('street');?>, <?php the_field('postal-code');?>, <?php the_field('city');?>';
    	geocoder.geocode( { 'address': address}, function(results, status) {
    	  if (status == google.maps.GeocoderStatus.OK) {

    		map.setCenter(results[0].geometry.location);
    		var marker = new google.maps.Marker({
    			map: map,
                        icon: image,
    			position: results[0].geometry.location
    		});
    	  } else {
    		alert('Geocode was not successful for the following reason: ' + status);
    	  }
    	});
      }
      initialize()
</script>

CSS

It is important to define length and height of the map-container to view the map inside the dom.

.map{
    width=100%;
    height=350px;
}

Result

INTERNETKULTUR | © 2018 | Imprint