Integrating Google Maps V3 into a VisualForce Page

I recently had a requirement to implement a Google Maps view for an Account and thought I would share the code I wrote to implement this functionality.

Firstly I needed to create a Visual Force Page containing the same structure as the default page, which is easy with just one line of code:

<apex:detail />

The rest of the implementation requires a bit of Javascript to convert the UK Postal code into coordinates and then generate the map.

To convert a Postal code into coordinates you need to use the geocoder object:

 var geocoder = new google.maps.Geocoder();
 geocoder.geocode({
   address: "{!Account.BillingPostalCode}"
   }, function(locResult) {
     var lat1 = locResult[0].geometry.location.lat();
     var lng1 = locResult[0].geometry.location.lng();
     var myLatlng = new google.maps.LatLng(lat1, lng1);
     var myOptions = {
       zoom: 14,
       center: myLatlng,
       mapTypeId: google.maps.MapTypeId.ROADMAP
     }
     var mapComp = document.getElementById("map_canvas");
     mapComp.style.width = '900px';
     mapComp.style.height = '500px';
     var map = new google.maps.Map(mapComp, myOptions); 
     var marker = new google.maps.Marker(
             {position: myLatlng, map: map, title: address});  
                 
 });

The code above also generates a map object which can be rendered on the page.

The complete code sample can be downloaded here (don’t forget to put your own API key into the code.

image

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Copyright FUNCODER 2021
Shale theme by Siteturner