+ Start a Discussion
robertcw777robertcw777 

Working Google Map Example?

I've done quite a bit of research on the forums on how to include a "simple" Google Map example, and have tried many of them. With all , I seem to end up in the same place as a lot of others end up based on the forum comments - the map never actually comes up. I have a valid API key that I substitute, and still nothing comes up - just a blank VF page. Does anyone have a real working example that I could review and modify?

 

 I just want to display a set of locations on the map. In my case, location is a custom object with country, state,city and zip (not a standard account record). If I can just get something basic working (i.e. actually see a map), I can then modify it to also set the marker colors based on some properties of the location - it's for a dashboard.

 

Any help would be greatly appreciated (something in API V3 would be best, but at least an example that works). I thought this was going to be simple...

Best Answer chosen by Admin (Salesforce Developers) 
Shiv ShankarShiv Shankar

1. Create a visual force page.

2. if you want to put visual force page as inline visualforce page for you account than you can use it.

3. Most Importan thing - the address which you are specifying in you account information field, it must be available on google map.(i should be pined on map). i have seen many people test google map with data whic in not already sticked on map.

<apex:page standardController="Account">

<head>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> 
<script type="text/javascript"> 

$(document).ready(function() {
  
  var myOptions = {
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: false
  }
  
  var map;
  var marker;
  
  var geocoder = new google.maps.Geocoder();
  var address = "{!Account.BillingStreet}, " + "{!Account.BillingCity}, " + "{!Account.BillingPostalCode}, " + "{!Account.BillingCountry}";
  
  var infowindow = new google.maps.InfoWindow({
    content: "<b>{!Account.Name}</b><br>{!Account.BillingStreet}<br>{!Account.BillingCity}, {!Account.BillingPostalCode}<br>{!Account.BillingCountry}"
  });

  geocoder.geocode( { address: address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK && results.length) {
      if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
      
        //create map
        map = new google.maps.Map(document.getElementById("map"), myOptions);
      
        //center map
        map.setCenter(results[0].geometry.location);
        
        //create marker
        marker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map,
            title: "{!Account.Name}"
        });
        
        //add listeners
        google.maps.event.addListener(marker, 'click', function() {
          infowindow.open(map,marker);
        });
        google.maps.event.addListener(infowindow, 'closeclick', function() {
          map.setCenter(marker.getPosition()); 
        });
        
      }
      
    } else {
      $('#map').css({'height' : '15px'});
      $('#map').html("Oops! {!Account.Name}'s billing address could not be found, please make sure the address is correct.");
      resizeIframe();
    }
  });
  
  function resizeIframe() {
    var me = window.name;
    if (me) {
      var iframes = parent.document.getElementsByName(me);
      if (iframes && iframes.length == 1) {
        height = document.body.offsetHeight;
        iframes[0].style.height = height + "px";
      }
    }
  }
  
});
</script>

<style>
#map {
  font-family: Arial;
  font-size:12px;
  line-height:normal !important;
  height:250px;
  background:transparent;
}
</style>

</head>
 
<body>
<div id="map"></div> 
</body> 
</apex:page>

 

All Answers

Shiv ShankarShiv Shankar

1. Create a visual force page.

2. if you want to put visual force page as inline visualforce page for you account than you can use it.

3. Most Importan thing - the address which you are specifying in you account information field, it must be available on google map.(i should be pined on map). i have seen many people test google map with data whic in not already sticked on map.

<apex:page standardController="Account">

<head>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> 
<script type="text/javascript"> 

$(document).ready(function() {
  
  var myOptions = {
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: false
  }
  
  var map;
  var marker;
  
  var geocoder = new google.maps.Geocoder();
  var address = "{!Account.BillingStreet}, " + "{!Account.BillingCity}, " + "{!Account.BillingPostalCode}, " + "{!Account.BillingCountry}";
  
  var infowindow = new google.maps.InfoWindow({
    content: "<b>{!Account.Name}</b><br>{!Account.BillingStreet}<br>{!Account.BillingCity}, {!Account.BillingPostalCode}<br>{!Account.BillingCountry}"
  });

  geocoder.geocode( { address: address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK && results.length) {
      if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
      
        //create map
        map = new google.maps.Map(document.getElementById("map"), myOptions);
      
        //center map
        map.setCenter(results[0].geometry.location);
        
        //create marker
        marker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map,
            title: "{!Account.Name}"
        });
        
        //add listeners
        google.maps.event.addListener(marker, 'click', function() {
          infowindow.open(map,marker);
        });
        google.maps.event.addListener(infowindow, 'closeclick', function() {
          map.setCenter(marker.getPosition()); 
        });
        
      }
      
    } else {
      $('#map').css({'height' : '15px'});
      $('#map').html("Oops! {!Account.Name}'s billing address could not be found, please make sure the address is correct.");
      resizeIframe();
    }
  });
  
  function resizeIframe() {
    var me = window.name;
    if (me) {
      var iframes = parent.document.getElementsByName(me);
      if (iframes && iframes.length == 1) {
        height = document.body.offsetHeight;
        iframes[0].style.height = height + "px";
      }
    }
  }
  
});
</script>

<style>
#map {
  font-family: Arial;
  font-size:12px;
  line-height:normal !important;
  height:250px;
  background:transparent;
}
</style>

</head>
 
<body>
<div id="map"></div> 
</body> 
</apex:page>

 

This was selected as the best answer
robertcw777robertcw777

Thanks! I can actually see the map :-)  One issue is that it I got a message saying that only secure content is shown, and the map came up after I clicked on "Show all Content". Do you know why?

colemabcolemab

Robert,

 

It is because that example was loading resources via a non-secure HTTP connection and the browser didn't load them until after you clicked ok.

 

For an example that uses v3 of google maps (and allows for https) please see this page.

 

Please note that my example expects your system to have the geocoding  (i.e. long / lat data) cached out (see an example here).  This is so you can map many points at once without hitting google API limits.

 

The previous example given by Shiv appears to make the geocoding call in real time which if you are mapping many many points can sometimes hit the API limits unless you have a paid API key.

 

Thanks

colemabcolemab

Correction, it looks like Shiv's example is using V3 as well but just doesn't load from a HTTPS connection.

Shiv ShankarShiv Shankar

As colemab said it might be the region, can you check with following script link

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script> 

 Just put this code instend on link which we have in our code.

robertcw777robertcw777
It works now. I changed the VF to the following:




Also, I set up https://maps.googleapis.com as a remote site on the security
settings.

And, colemab, thank you for the tips on the geocoder.

You guys saved me from days of effort and frustration. Much appreciated!
robertcw777robertcw777

Here are the missing lines in the above.

 

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

 

 

R DraperR Draper

Thanks for the script.  It works great except for the fact that if your street field has a line break of any kind it stops working.  I have done much research into this and tried everything from JSENCODE, replace, unescape, urlencode.  Nothing seems to work.  I always get a syntax error in the dev console that looks like it's only getting the first or second part of the street.  I'm sure I'm not the only one trying to find a solution to this.

colemabcolemab

Draper,

 

Here is an example of a javascript function that will clean up string's for use with the geocoder:

 

        function CleanString(DirtyString) {
        	
        	// replace cr/lf with space
        	DirtyString = DirtyString.replace(/(\r\n|\n|\r)/gm," ");
        	
        	// remove leading and trailing commas
        	DirtyString = DirtyString.replace(/(^,)|(,$)/g, "");
        	
        	// remove leading and trailing dashes
        	DirtyString = DirtyString.replace(/(^-)|(-$)/g, "");
        	
        	return DirtyString;
        	
        } // end clean string

 

Of course you would need to modify your page / script to call this funciton.

 

I hope this helps.

R DraperR Draper

Ok, I figured out why it wasn't working!  You have to put your code: {!SUBSTITUTE(JSENCODE(Contact.MailingStreet),'\r\n',' ')} in the address variable AND in the marker code.  It was breaking in the marker code because it still had the returns in the street field.  Hope other people find this post for the soution:)

Devashree TidkeDevashree Tidke
@Shiv Shankar: I am getting Error Error: GoogleMapTry line 5, column 37: The value of attribute "src" associated with an element type "script" must not contain the '<' character
Error Error: The value of attribute "src" associated with an element type "script" must not contain the '<' character.

Thomas PanniThomas Panni
Just write it this way:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

and it works. Had the same problem....for me it works fine. Do not forget to set the Remote Site Settings appropriately.

best Thomas
s shekars shekar
hi, i can able to save without errors and i click preveiw in visualforcepage i am getting error as 
Oops! 's billing address could not be found, please make sure the address is correct.

how can i get particular account id billing address? can u please send what to do?

thanx waitin for ur reply
 
Arpit Sethi 9Arpit Sethi 9
Thanks for sharing..its working perfectly :)