Sunday 11 December 2016

Google Maps Integration with AEM Page

Ever wondered how does entering the pin code or address on any mobile application gives out the google map of the location !!
Here you go... It's a simple integration with Google Maps API. Yes!! this can be done on any platform easily. Take a look in the below screenshot how does it appear to the end user.


Here's a example to it using the pin code as the user data and give him the location on the map.

Step 1:
Create a component and add the following code which generates a form on the page with a submit button.
Fields on the dialog can be the title you want to give for the map which is a simple text widget.

<div class="container">
   <h2>Search stores</h2>
<label for="Enterzipcode">Enter store zipcode</label>
        <input id="zipCode" type="text">
        <input type="hidden" id="miles10" name="miles" value="${properties.miles}" />
        <button class="btn btn-info" id="submitZip" onClick=getLocation() >Submit</button>

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


Step 2:
Create a project specific clientLib structure. And a folder to add all the js files required.
Create a file named geomap.js and add the below code.

<script>
function getLocation(){
    var zipcode = $('#zipCode').val();
    $.ajax({
       url : "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:"+zipcode+"&sensor=false",
       method: "POST",
       success:function(data){
           latitude = data.results[0].geometry.location.lat;
           longitude= data.results[0].geometry.location.lng;
   initMap(latitude,longitude)
       }
    });

};
   
function initMap(latitude,longitude) {

        var city = {lat: latitude, lng: longitude};
        var map = new google.maps.Map(document.getElementById('map-canvas'), {
                      zoom: 10,
                      mapMaker: true,
                      rotateControl: true,
                      center: city
                  });
        var marker = new google.maps.Marker({
                    position: city,
                    map: map
                 });
      }
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyChxoSa2XZNTPZHs1UUuA24vfEAZhm3JRc">
</script>

Make sure the above google api key is generated and added in the js file.


Step 3:
Can add the custom css to the map section which fits on the site page. Below is the sample css added to the map.

<style>
       #map-canvas {
               height: 400px;
               width: 100%;
       }
</style>

Output:

On the initial page load , a form is seen with a input field for pin code and a submit button.


On entering the pin code and click on " submit ", an ajax call will bring in the map of the entered pin code as below.

The map comes with controls like Zoom in and Zoom out.

No comments:

Post a Comment