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:

<span class="kwrd">&lt;</span><span class="html">apex:detail</span> <span class="kwrd">/&gt;</span>

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:

<span class="kwrd"> var</span> geocoder = <span class="kwrd">new</span> google.maps.Geocoder();
   address: <span class="str">"{!Account.BillingPostalCode}"</span>
   }, <span class="kwrd">function</span>(locResult) {
     <span class="kwrd">var</span> lat1 = locResult[0];
     <span class="kwrd">var</span> lng1 = locResult[0].geometry.location.lng();
     <span class="kwrd">var</span> myLatlng = <span class="kwrd">new</span> google.maps.LatLng(lat1, lng1);
     <span class="kwrd">var</span> myOptions = {
       zoom: 14,
       center: myLatlng,
       mapTypeId: google.maps.MapTypeId.ROADMAP
     <span class="kwrd">var</span> mapComp = document.getElementById(<span class="str">"map_canvas"</span>); = <span class="str">'900px'</span>; = <span class="str">'500px'</span>;
     <span class="kwrd">var</span> map = <span class="kwrd">new</span> google.maps.Map(mapComp, myOptions); 
     <span class="kwrd">var</span> marker = <span class="kwrd">new</span> 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.


Copyright FUNCODER 2018
Shale theme by Siteturner