How do you integrate an interactive Google Map into Salesforce Accounts / Leads? - Answers - Salesforce Trailblazer Community
Trailblazer Community
Ask Search:
Dan StoneDan Stone 

How do you integrate an interactive Google Map into Salesforce Accounts / Leads?

Visual force
Best Answer chosen by Moderator (salesforce.com) 
Dan StoneDan Stone
- Use Visual Force to add a live, interactive Google Map with zoom controls and maptype select buttons to Salesforce Accounts and Leads and other detail record pages:



Go to Your Name » Setup » Develop » Pages

Copy/paste the following code into a new Page replacing what appears by default.  Notice that in this example we're using custom fields for the Account address components:

<apex:page standardController="Account">
<apex:pageBlock >
<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: 20,
    mapTypeId: google.maps.MapTypeId.HYBRID,
    mapTypeControl: true
  }
  
  var map;
  var marker;
  
  var geocoder = new google.maps.Geocoder();
  var address = "{!Account.Project_Street_Address__c}, " + "{!Account.Project_City__c}, " + "{!Account.Project_Zipcode__c}";
  
  var infowindow = new google.maps.InfoWindow({
    content: "<b>{!Account.Name}</b>"
  });
 
  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 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:500px;
  background:transparent;
}
</style>
 
</head>
 
<body>
<div id="map"></div> 
</body> 
</apex:pageBlock>
</apex:page>


Live interactive Google Map in Salesforce Account detail page

 

All Answers

Dan StoneDan Stone
- Use Visual Force to add a live, interactive Google Map with zoom controls and maptype select buttons to Salesforce Accounts and Leads and other detail record pages:



Go to Your Name » Setup » Develop » Pages

Copy/paste the following code into a new Page replacing what appears by default.  Notice that in this example we're using custom fields for the Account address components:

<apex:page standardController="Account">
<apex:pageBlock >
<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: 20,
    mapTypeId: google.maps.MapTypeId.HYBRID,
    mapTypeControl: true
  }
  
  var map;
  var marker;
  
  var geocoder = new google.maps.Geocoder();
  var address = "{!Account.Project_Street_Address__c}, " + "{!Account.Project_City__c}, " + "{!Account.Project_Zipcode__c}";
  
  var infowindow = new google.maps.InfoWindow({
    content: "<b>{!Account.Name}</b>"
  });
 
  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 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:500px;
  background:transparent;
}
</style>
 
</head>
 
<body>
<div id="map"></div> 
</body> 
</apex:pageBlock>
</apex:page>


Live interactive Google Map in Salesforce Account detail page

 
This was selected as the best answer
Jason BenkertJason Benkert
I am trying this and the map is not showing.  Only an empty space.  Any thoughts?
Dan StoneDan Stone
You can easily use the standard salesforce Billing or Shipping addresses as follows (see bold section):

<apex:page standardController="Account">
<apex:pageBlock>
<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: 20,
    mapTypeId: google.maps.MapTypeId.HYBRID,
    mapTypeControl: true
  }
  
  var map;
  var marker;
  
  var geocoder = new google.maps.Geocoder();
  var address = "{!Account.ShippingStreet}, " + "{!Account.ShippingCity}, " + "{!Account.ShippingPostalcode}";
  
  var infowindow = new google.maps.InfoWindow({
    content: "<b>{!Account.Name}</b>"
  });
 
  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 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:500px;
  background:transparent;
}
</style>
 
</head>
 
<body>
<div id="map"></div> 
</body> 
</apex:pageBlock>
</apex:page>
Jaime EsparzaJaime Esparza
change http for https
Jaime EsparzaJaime Esparza
can you tell me how to get the latitude and longitude values ​​and store them in fields salesforce? that code would need? thanks ...
Dan StoneDan Stone

@Raul Flores you don't need Lat/Long values for this to work, just an address.  If you're asking how to find lat/long values for a point where there is no address, there are a number of sites such as http://www.doogal.co.uk/LatLong.php that let you click on map and get the lat/long for the point.

Jaime EsparzaJaime Esparza
thanks but not if you help me as I get to save data in salesforce map a field such Latitud__c and I want to keep the value obtained from the map? if you understand me? thanks ...
Dan StoneDan Stone
@Raul Flores:  I'm not sure how to automatically get Lat/Long values from a map into Salesforce fields, but if you want to generate Lat/Long values by clicking on a map within Salesforce, you could reverse engineer the following map and then modify the code above to add it to the Account detail page, for example.  See:  http://360villagevirtualtours.com/maps/latlong.html
Arun kadaralaArun kadarala
Iam looking to navigate to respective account detail page If I click one of many markers in google map.
How to do that.?
Bryan RevelantBryan Revelant
In this case dont you have to write a custom controller in order to create a list of ID's in order to get the map to pull up. Other wise this will come up to a blank map unless you have a id.

Can you use this with Flow to get ID?
Peter Jan de FijterPeter Jan de Fijter
Hi Dan Stone, 
This Visual Force page is working great.
Can you help me with this:
The visualforcepage (including script) is marked as 'insecure' by chrome/ie/etc... So every time I startup my browser I have to manually allow the javascript to run. Is it possible to change the script in order to avoid this message in browsers?
Dan StoneDan Stone
Try changing http to https per @Raul Flores' suggestion above.
Kapil PKapil P
Hi Dan Stone,
Is m right it's only work for IE ....i.e. i m getting browser issues. Its working fine with IE bt not able to view in other browser.
Please clarify that ... how it will work for other browser like mozila, chrome ... :)

Thanks,
Kapil




Amritha AMAmritha AM
Hi Dan,

Is it possible to see all accounts or leads in google map

Thanks
Amritha
Dan StoneDan Stone
There are very good mapping offerings now in the Salesforce AppExchange:  https://appexchange.salesforce.com/results?keywords=map
Adrian CroninAdrian Cronin
Dan,

thanks for this. I put your 2nd iteration of code in and it accepted it fine (no errors) but I don't see the map appearing when I view the Account. I'm relatively new to salesforce (but not IT)so apologies in advance if this is a basic question. Do I have to do any other config to get this working? It's marked as active.

thanks.
Adrian
Anderson Leão GimenesAnderson Leão Gimenes
Hello Dan, like this ...

I used your code in my base and tried with all fields for the address on how ACCOUNTS and LEADS, but the result doesn't show up.
Tested with custom fields, but nothing worked, there's something more to be done to the code work?
Avni PatelAvni Patel
I am experiencing the same problem nothing appears on the accounts or leads page. I am using the Professional edition not sure if this aimed at any particular edition of Salesforce. Would be great if we could get this looks fab
John MaherJohn Maher
Hi Dan,
Thankyou for the code, after some twitching around with the https and the "Billing Address" I have got it to work in my Accounts.
Is there any way you could have included the option for the user to click on link to get directions to the pin ? This would be ideal for a "Sales Team" on attending appointments. I am looking of auto emailing my sales team, their appointments when made by the telesales team.
Thank you again
Anderson Leão GimenesAnderson Leão Gimenes
The msg that pops up is this: "the link accessed is not valid. This page requires a confirmation key of the CSFR, has some security to be enabled?


Avni PatelAvni Patel
I just get a blank screen, also not to sure how to modify the coding for billing Zip/Postal Code as it does not accept the forward slash. If i leave it without the forward slash then it does not recognise the field, however on the account the field is Billing Zip/Postal Code. I think this maybe the reason why the map is not displaying. Does anyone have any suggestions?
Allan WaltemyerAllan Waltemyer

John, although we do not have outside sales, we use the coordinates derived from the following free app (and Google Maps) to determine proximity of businesses to each other - The Find Nearby app contains a directions option... but has restrictions per browser etc.:

https://appexchange.salesforce.com/listingDetail?listingId=a0N30000001gpWhEAI

If you have a budget for it, the folks over at GeoPointe should have a great solution for you! 

https://appexchange.salesforce.com/listingDetail?listingId=a0N300000016ZHeEAM

Josh SchmitzJosh Schmitz
Dan,

Thanks for the code can't wait to test it out on my custom objects. One question before I get to far into it though.

Is it possible to Load an existing map instead of creating a new map per record?  So Basically use something like the "My Maps" feature of google so I can still see the surrounding pins that I have in my org?  Lets say I have 10 Opportunities in a certain area, I still want to be able to see them on my map and maybe even have a couple different style pins so I can tell the probability of each Oppty.

Thanks again!
sfdc ianesfdc iane
Thanks @dan its working for me .....
Iain ClementsIain Clements
This is brilliant @Dan - many thanks for putting this code on there. This is a great 5 minute enhancement that I think our users will really like - thanks once again for sharing.
Alan GuedesAlan Guedes
Thanks a lot for sharing this, @Dan! I've successfully implemented for my accounts object as well as a custom object.

It works perfectly for users with "System Administrator" profiles, but not for the others. When I try to view the page "logged in" as any other profile I see the following message "Oops! XXXXXX's address could not be found, please make sure the address is correct." But the map comes up correctly "logged in" as a System Administrator.

I have already enabled access for all profiles to the page. Before doing that, the message was that the user had insuficiente privileges.

I appreciate if you can help!
Chris UttleyChris Uttley
After installing, it all worked great, but I found the address Marker (the red circle/arrow) on the map wasnt visible, maybe because of my zoom level.
So I added the PANBY function so that the address marker would be exactly centred in the visible map window.

//center map
        map.setCenter(results[0].geometry.location);
        map.panBy(0,200);
Bill PflumBill Pflum
Can I ask where exactly in the code you add this?
Bill PflumBill Pflum
Dan,

Is there a way to have it defaul to Map view rather than Satellite view?  

-Bill
Bill PflumBill Pflum
Chris,

Can I ask where exactly in the code you add the code you specified to center the map?  I'm not a developer (just a sales person) so while I've gotten this to work (to my amazement), I wasn't able to get your centering feature to work.  

//center map
        map.setCenter(results[0].geometry.location);
        map.panBy(0,200);

Thanks for your help.

-Bill
Alan GuedesAlan Guedes
@Bill Pflum,

To change the "type of map" from "satelite" to the "regular map", you have to change the "HYBRID" to "MAP" on the following line:
 

mapTypeId: google.maps.MapTypeId.HYBRID,

change to

mapTypeId: google.maps.MapTypeId.MAP,
 
Good luck!

Alan
Stephen MorrisStephen Morris
This map is wonderful. Is there any way to make the map pull from the Billing address first, and if it's not populated, pull the map from the Shipping address?
Chris UttleyChris Uttley
@Bill Pflum,
You asked where the code goes to pan the map to make it center better.
You will notice in Dans code that he has a few lines where it says //centre map
I put my code right there.
You may have to play with the values in the map.panby statement.....to the point where you are happy with the centering.
uday kumar karekalluuday kumar karekallu
@Dan ,

I am getting blank page, used the same code as you given and created custom fileds of Address and city and PIN as you used in code for Account. and added VF page in Page layout..Thanks in Advance :)
Neighborworks SupportNeighborworks Support
Hi @ Dan,
We are using Text area field for street on our accounts and the map is not loading when users enter the street name using line breaks. i am trying to solve this issue using Java script but did not come up with a proper solution. Can you sugest me something here??
Kayla TownsendKayla Townsend
Curious as to where to find develop under the set up tab?
Dan StoneDan Stone
Use the Quick Find box in the upper-left.
Raj JhaRaj Jha
Hello Dan, 

You can do this on a field level also. No need of visualforce page. Please review this link -
http://salesforcedesk.blogspot.in/2013/07/google-map-on-field.html

Thanks.
Katelyn ShelleyKatelyn Shelley
This would be amazing! Unfortunately it is showing up blank on my page. Any ideas (non-developer).

Thanks!
Dan StoneDan Stone
Try changing http to https per @Raul Flores' suggestion above.
Dan StoneDan Stone
@Raj Jha the field level map you reference is a great way of inserting a non-interactive google map without zoom/pan capability.
Katelyn ShelleyKatelyn Shelley
One of my users is having this issue - You do not have sufficient privileges to access the page: /apex/PageLead ?
Chris WhiteheadChris Whitehead
@Katelyn Shelly Does this user have a full Salesforce license?
Katelyn ShelleyKatelyn Shelley
@Chrie Whitehead. Yes they do -thats why I am a little confused. 
Katelyn ShelleyKatelyn Shelley
Here is the code I used (I updated everything that said Account to Lead and added the centering). 

<apex:page standardController="Lead">
<apex:pageBlock >
<head>

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

$(document).ready(function() {
 
  var myOptions = {
    zoom: 20,
    mapTypeId: google.maps.MapTypeId.MAP,
    mapTypeControl: true
  }
 
  var map;
  var marker;
 
  var geocoder = new google.maps.Geocoder();
  var address = "{!Lead.Street}, " + "{!Lead.City}, " + "{!Lead.Postalcode}";
 
  var infowindow = new google.maps.InfoWindow({
    content: "<b>{!Lead.Name}</b>"
  });

  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)
     
       
        map.setCenter(results[0].geometry.location);
       
        //center map
        map.setCenter(results[0].geometry.location);
        map.panBy(0,200);
       
        //create marker
        marker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map,
            title: "{!Lead.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! {!Lead.Name}'s 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:500px;
  background:transparent;
}
</style>

</head>

<body>
<div id="map"></div>
</body>
</apex:pageBlock>
</apex:page>
Dan StoneDan Stone
I cut and pasted your code in a demo org and worked for me with one exception - there's an dangling " at the very end that must be removed.
Katelyn ShelleyKatelyn Shelley
Hi Dan - not seeing where that is. It is working for me as well but not for my users. Is there a particular profile setting that needs to be in place?
Katelyn ShelleyKatelyn Shelley
Hi @Dan Stone - I had to enable the visualforce pages for a few profiles. Thank you so much for responding and helping me out!
Vuk DukicVuk Dukic
This is great!!!   Thank you!
Amanda ReamAmanda Ream
@Dan Stone! You are the Man! Thanks for sharring this!
Ryan YoungRyan Young
I created a custom link that Google Maps the company name in that particular city and state. Once clicked it opens in a new window and people can navigate from there.
Chris DurkeeChris Durkee
Can someone tell me where in here to make the map larger on the account page? 

its quite a small section.  i would like it to be a little larger.

thanks for any help



<apex:page standardController="Account">
<apex:pageBlock >
<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: 17,
    mapTypeId: google.maps.MapTypeId.HYBRID,
    mapTypeControl: true
  }
 
  var map;
  var marker;
 
  var geocoder = new google.maps.Geocoder();
  var address = "{!Account.BillingStreet}, " + "{!Account.BillingCity}, " + "{!Account.BillingPostalcode}";
 
  var infowindow = new google.maps.InfoWindow({
    content: "<b>{!Account.Name}</b>"
  });

  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' : '60px'});
      $('#map').html("Oops! {!Account.Name}'s 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:200px;
  background:transparent;
}
</style>

</head>

<body>
<div id="map"></div>
</body>
</apex:pageBlock>
</apex:page>
Dan StoneDan Stone
To change the allocated space for a Visualforce component (page) on a record detail page, pull up one record (e.g., an account) and then click the "Edit Layout" text link in the upper right, which will take you to the screen below.

Hover over the VF component and then click the wrench icon:

Edit Layout to Change VF Component Dimensions
Katy LawrenceKaty Lawrence

Dan,

This code is not working for me. Do I have to purchase an app for this to work? Also, there's nothing on Salesforce that says "Account," my version says "Company."

Please help if you can! Thanks!

Alan GuedesAlan Guedes
Thanks a lot for sharing this, @Dan! I've successfully implemented for my accounts object as well as a custom object.

It works perfectly for users with "System Administrator" profiles, but not for the others. When I try to view the page "logged in" as any other profile I see the following message "Oops! XXXXXX's address could not be found, please make sure the address is correct." But the map comes up correctly "logged in" as a System Administrator.

I have already enabled access for all profiles to the page. Before doing that, the message was that the user had insuficiente privileges.

I appreciate if you can help!
Dan StoneDan Stone
@Alan Guedes please see this Help page and let me know if it solves your problem:

https://help.salesforce.com/HTViewHelpDoc?id=users_profiles_visualforce_access.htm&language=en_US (https://help.salesforce.com/HTViewHelpDoc?id=users_profiles_visualforce_access.htm&language=en_US)
Alan GuedesAlan Guedes
Thanks, @Dan Stone, I actually did that initially, when I had the "insufficient privileges" message. Now, apparently the profiles do have access, however, the message is "Oops…". So, apparently, they are executing the visual force page. I thought the access to "Billing Address" field could be the problem, but they have "Modify All" permission. Any other ideas appreciated.
Chris UttleyChris Uttley
Here is an interesting issue..I have an Office Address set of fields, and the map works perfectly for most of my U.S. and Canada addresses.
However, for this particular Wisconsin address, the map shows Manilla in the Phillipines!
Any idea why?

Street = City County Building, Rm106A, 210 Martin Luther King Jr Blvd
City = Madison
State = WI
Zip = 53703
Country = USA
Guha ArumugamGuha Arumugam
@Dan Stone:
Hey Dan, I have issue in viewing the page in my account detaols record. Am getting an error message on the page like"Content cannot be displayed: The link you followed isn?t valid. This page requires a CSRF confirmation token. Report this error to your Salesforce administrator."

I have just copy pasted your code to see how it works. But am stuck with this error.

Can anyone Please help with this issue?.

User-added image
Guha ArumugamGuha Arumugam
Finally Resolved.... :) I removed the check mark for CSRF in VF page creation view. and it worked.... Thanks for Awesome Idea @Dan Stone
Vish RaoVish Rao
I am getting this error - need help in 
 User-added image
Dan StoneDan Stone
Vish, you need to modify the code to jive with your field names.
Mike ClassyMike Classy
i am using one free app from appexchange for above purpose which works great .
Samuel BeckerSamuel Becker
Dan,

Awesome, this is really neat.  Very helpful, people like you are why SFDC and this community can get so much done.  Thank you.

1 question though.  I set this up on my Mac using safari and it works great.  However when I asked a co-worker on PC using Firefox to test it all they see is a blank screen where the map shoudl be.  I asked them to test in IE and they got the same thing.  Why would it be working just dandy on Safari on a Mac and not on a PC using either Firefox or IE?
Chad MacKayChad MacKay
Is there away for this to show up for Contact's as well?
Eli KuslanskyEli Kuslansky
I am getting same error as Vish. Seems like you have custom fields which I don't. Tried tweaking to match default fields but maybe my lack of knowledge. Can't get this wonderful addon to work.
Eli KuslanskyEli Kuslansky
Figured it out and got it to work. Brilliant contribution!
Brian LiederBrian Lieder
I have very limited knowledge of writing code and was able to get this to work on accounts and leads.  No way would this have been possible without this post.  I just had to say thank you Dan Stone, i now look like a super hero to my boss!  Its people like you that help SF become such a great success, and i think i speak for hundreds (if not thousands) of people when i say THANK YOU!!!!
Chris UttleyChris Uttley
Its a great feature, but there is one usability issue my users have complained about.

I have an Address section about midway down the Account page layout, and thats where the map is located.

So when a user first opens an account page, as they scroll down the page, often time the cursor ends up inside the map area, and instead of scrolling down the page, they end up zooming out of the map....and they have to move their cursor off the map and then continue scrolling. Of course it totally depends on where the cursor is when they begin scrolling down.

It's a small pain for a very common function (scrolling), and I dont have any suggestions for improving the user experience.

If anyone else has experienced this and has any thoughts, would love to hear them.
Jo-CEO DengJo-CEO Deng
@Chris Uttley,

Add

scrollwheel: false

after "mapTypeControl: true" in a new line
Justin Manchester4Justin Manchester4
Just as a note, this can be completed in a smple Formula Field /Text returrn:

HYPERLINK(
http://maps.google.com/maps?q=&
MailingStreet
&
",+" &
MailingCity&
"+"&
MailingState&
"+"&
MailingPostalCode&
"&t=m&z=16",
IMAGE(
"http://maps.google.com/maps/api/staticmap?center="&
MailingStreet&
",+" &
MailingCity&
"+"&
MailingState&
"+"&
MailingPostalCode&
"&zoom=11&format=png&maptype=roadmap&mobile=false&language=English&markers=|color:Green|label:Address|"&
MailingStreet&
",+"&
MailingCity&
"+"&
MailingState&
"+"&
MailingPostalCode&
"&size=900x300&key=&sensor=false","Google Maps"))
Edward BerwickEdward Berwick
Thanks for posting this Dan, it works great. Would you/the rest of the group know how I can extend this to an Account Hierarchy e.g. we have a HQ account and a number of Subsidiaries scattered throughout the country - it would be cool to be able to view a map of the country with pins denoting the various locations based upon the accounts in a company hierarachy. Denoting the HQ as a different coloured pin etc. Thanks again. 
Darren BraddockDarren Braddock
Fantastic thank you

Just one question, how do i make the map, the full wifth of the page as per the screenhot?
Harsh ChaturvediHarsh Chaturvedi
Hi I am unable to get the maps on the detail page. Its coming blank. please some one help me out.

  User-added image
Amanda ReamAmanda Ream
@Edward Berwick, there is a really great app on the AppExchange called GeoPointe that will allow you to map not only Accounts but any other SF data. You can also change the colors of the pins based on parameters you select. Here's the link: https://appexchange.salesforce.com/listingDetail?listingId=a0N300000016ZHeEAM
priyank rajvanshipriyank rajvanshi
@Chris Uttley

i have checked your location. it is showing correct map location... 
priyank rajvanshipriyank rajvanshi
@Dan Stone
 thanks a lot.... :) it is working excellent.
Chris UttleyChris Uttley
@priyank rajvanshi

Thanks for checking priyank, but the address I gave does NOT show the correct location on the google maps. Here is an image showing the map that I get for a location in Madison Wisconsin.....the map is showing a location in Manila Phillipines! Very strange.An address is Madison Wisconsin that displays a map in Phillipines
Paula NelsonPaula Nelson
I am a newbie. (Day 5 of my Salesforce journey!)  Forgive me if I ask really dumb questions!

Is this something I can use with SalesforceFoundation edition?  In order to learn to learn Salesforce I volunteered to do a data migration from an ACT CRM to Salesforce for our inhouse education and marketing teams.  There is a lot of fear from some of the long time ACT users.  I understand that so am trying to do a really good job.

When I saw this answer I thought right away that this could give me the "tipping point" that I am looking for in user acceptance.  I am thinking that when they set up a seminar they could use this to "see" which instructors (contacts) are close by and which prospective participants (leads and contacts) to contact about the seminar.

Am I on the right track?

Brian LiederBrian Lieder
What if I wanted to take it up a notch?  I have a mappoint file (or could be any file for others' orgs) containing locations of other customers of ours that i would love to either overlay on this map, or replace with this map.  How feseable would this be?  Perhaps there is some code that i could copy and paste the other customer's locations in, or code that i could paste the file into?  Just some thoughts to make this awesome feature more functional....
Chinnu salesforceChinnu salesforce
Hi i am getting this error - need help on this...User-added image
Michael AllenMichael Allen
I've built a VF page in our sandbox today and this works an absolute treat! Have put in a few mods to open it in a new window without header or sidebar (eg. Line 1 now reads <apex:page standardController="Account" sidebar="false" showheader="false"> ), and chose to launch the VF page from a custom button (eg: https://c.cs17.visual.force.com/apex/Accounts_Map?id={!Account.Id} ) rather than having a component on the page layout.

Like Brian Leader, I too would like to pass multiple accounts for geo coding at one time. How can this be achieved within the code. Can I pass it a string of the acct ID's in the URL I want from a custom field?

Would also be great to pass hyperlinks to Google Maps:
eg "title: <a href="https://cs17.salesforce.com/00100000AbcDe">{!Account.ID}!</a>" but this doesn't seem to work. Any hints? Must be a quick fix??

As a final mind blowing feature, it must be possible to create markers of different colours? If so, I'd like to make these dependent on the Account Status (picklist), so active accounts would have green markers, cold accounts blue, etc. Have searched and hacked for a bit but am drawing a blank on the code to do this...
Chris LanceChris Lance
Amazing work, thanks Dan!  One little piece I added was a max zoom setting under the "//add listeners" section:

google.maps.event.addListener(map, 'zoom_changed', function() {
          if (this.getZoom() < 3) this.setZoom(3);
        });

I think this helps keep the map from looking silly if you slide the min zoom all the way down. 


---------------------------------------
To answer the people who are only getting a blank map, change the http to https.

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


---------------------------------------
For the people getting the invalid field "Project_Street_Address__c" error, you need to change the address to reference your address field names.  So for Account, if you're just using standard billing fields:


var address = "{!Account.BillingStreet}, " + "{!Account.BillingCity}, " + "{!Account.BillingPostalCode}";
Nathan LindstromNathan Lindstrom
Hi this is great. Do you know how we can add geo-location into the code for latitude and longitude?
Chris LanceChris Lance
Another reason people might be getting blank maps is from text area fields (BillingAddress) with character returns etc.  Updating line 21 to wrap my text area field in a !JSENCODE() fixed this.

var address = "{!JSENCODE(Account.BillingStreet)}, " + "{!Account.BillingCity}, " + "{!Account.BillingPostalCode}, " + "{!Account.BillingCountry}";

http://www.salesforce.com/us/developer/docs/apexcode/Content/pages_security_tips_scontrols.htm
Chris LanceChris Lance
I like this one too - zoom out if the street is missing:

    zoom: {!IF(Account.BillingStreet == NULL,5,20)},

Greg JarrettGreg Jarrett
In response to Nathan's question about doing this with GEOLOCATION fields, it can be done by converting the GeoLocation field to a text value as a separate hidden field in the object. 

1. Create a custom FORMULA field (return type = TEXT) on your object. Lets call this field "coordTEXT" Make its default value equal to:

TEXT(geolocationField__Latitude__s)&" "&TEXT(geolocationField__Longitude__s)

(make sure you replace "geolocationField" with your custom field name)
(The VF page can reference this TEXT field (It is not able to reference a GEOLOCATION field for me))

2. Instead of using "var address = Billing Address, Street Address etc" in the VF page, use this:

var address = "{!Custom_Object__c.CoordTEXT__c}";

(make sure you replace "Custom_Object__c" with your own custom/standard object name, and don't forget the semi-colon at the end)

Troubleshooting:

- If you get blank space on the rendered page, make sure http: is set to "https:" in the VF page
- I received an SOQL query error for the text field, which was fixed by including the following line beneath apex:page:

<apex:outputText value="{!Custom_Object__c.CoordTEXT__c}" rendered="false" />



Mani RMani R
I need multimple markers of the different Accounts on the Map..How can we do this??
Greg JarrettGreg Jarrett
HI Mani, there are quite a few apps on the AppExchange that will do a really good job of this for you across different SF licence versions, across both standard and custom objects - https://appexchange.salesforce.com/results?filter=a0L3000000OvSOYEA3
Kalyan ChakravarthyKalyan Chakravarthy
MAp ErrorHi All, When i copy the map link and past in my slaesfore i am below error, can any one help me?
 
Ben MervenBen Merven
This is working great for me, thanks for the help!
One issue is that the coordinates are not quite working properly. For example, I center my office on the google maps web app, then copy and paste the coordinates into the Salesforce record. When I then view the record, the pin is about 100m from where it should be. 

I should note I'm using the GPS Coordinates field, and converting this to text as per Greg Jarret's instructions above. I notice that the converted text coordinates (which are in decimal degrees) are only to 5 decimal places, whereas google maps uses 7 decimal places, which would account for the wrong location on the map.

Does anyone know how to fix this?
Thanks
Greg JarrettGreg Jarrett
Hi Ben, what output are you getting on the standard salesforce page layout if you make the 'coordTEXT' field visible? Do you get 7 decimal places as per below:
User-added image
Ben MervenBen Merven
Hi Greg,

Your question partially answered my question, I had set the wrong number of decimal places! I've fixed that, but still having the issue with the pin being in different places. See comparison below:

First images straight from google maps (using the coordinates as the search term):

Google search term

Google maps - searched using the coordinates


Second images (coordinates as saved in Salesforce and the location as shown in the visualforce page:

Coordinates from salesforce

Visualforce rendered map
Greg JarrettGreg Jarrett
Hi Ben, thats a tough one. I've checked my setup and I've actually got accuracy to 8 decimal places - but I can only do that because the source database I've used for my geolocations provides that level of accuracy. Unfortunately I think the solution is beyond my technical ability :(
Ben MervenBen Merven
Hi Greg,
No worries, thanks for your help either way. Perhaps you know, but is this vidualforce code using the latest Google Maps API? I know that they update it every now and then, which is perhaps the reason for it rendering incorrectly (although, doesn't explain why your works fine??).

Anyway, hopefully someone else has an answer.

Thanks again
Ben
Greg JarrettGreg Jarrett
Thats a good question, I can't see where it specifies a version of the API in my VF page: 

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

so I presume it is the most current version, but I could be wrong....
Ben MervenBen Merven
Yeah I just tried using the API v3 (which is the latest) and it still didn't work. Will keep trying!
Ben MervenBen Merven
I just tried removing the code for the panby, ie the following code:

//center map
        map.setCenter(results[0].geometry.location);
        map.panBy(0,0);

I removed this code, saved the page, then reloaded my record. The map centered correctly and the pin was in the right place. Then I reloaded the record page (just to doulbe check) and the map went back to being incorrect.

Have tried to replicate this but to no avail. Definitely something funny going on with the code.
kamal raokamal rao
i got blank page not showing map 
 User-added image
kamal raokamal rao
yes i got when replase "http to htpps " and creat two custam field city ,state
Brian CuccaroBrian Cuccaro
Hello. Great thread! I tried pasting the recommended code at the beginning of this thread, but I receive an error: Error: Invalid field Project_Street_Address__c for SObject Account

Any suggestions? (I am using the Group edition. Hopefully that doesn't matter)

Brian
Brian CuccaroBrian Cuccaro
I managed to get the map to display on my "Account" page, but it is blank. Any suggestions? I tried it with IE and Firefox with the same results. Any Ideas?

Lee MoreauLee Moreau
Hi everyone I got this working, we have Group edition, but I'm an administrator and any of my users that are normal users can't acceess the maps, it says "Insufficient Privilidges"  There's no way to change permissions etc with group edition, so is there any idea why it might not work for them?
Chris LanceChris Lance
@Lee

Under Develop > Pages in Setup, try clicking the Security link next to the page - you probably need to add the non Sys Admin profiles to it.
Lee MoreauLee Moreau
Worked thanks!!!
Manjunath VManjunath V
While running a code in vf page am getting blank page, i need steps to get the result...plz
SS FFFSS FFF
Hi Manju

You should place vf page in as inline vf page or else you should pass record id in url

Ex : https://c.na15.visual.force.com/apex/GoogleMapInt?id=90630000000guBk(Ur's record id)
priyank rajvanshipriyank rajvanshi
@Chris Uttley

yeah u were right your given address is showing location of manila...
but if you remove building name that is- City Country Building,Rm106 A
you have to save only- 210 Martin Luther King Jr Blvd
Madison, WI 53703
United States Of America

then it'll show exact location.area map
Adam BoyceAdam Boyce
This worked a treat for me, thank you so much!

Is there anyway we can enhance the functionality? Similar to what is here:

https://www.youtube.com/watch?v=2U9hNhkL2kU

At a mimimum it would be very useful if we could map all of our records on the one map and also be able to plan directions on the map as well. Also distance.
Greg JarrettGreg Jarrett
Hi Adam, there are a few apps (which are affordable) on the AppExchange that will take care of the stuff you're looking for - directions, mapping lots of records, custom objects etc. Geopointe and MapAnything are two that come to mind. 
Mark SmithMark Smith
Thanks Dan. Could this process be used to display google streetview somehow? 
Anne SquireAnne Squire
Used Michael Allen's awesom suggestion and instructions above and created a custom button - only issues are I have to zoom out a fair amount once the page displays and it doesn't open in a new tab or window.

If anyone figures out how to load multiple accounts in the same parent account view, that would be awesome.
Anne SquireAnne Squire
Actually, I take second issue back. Going from sandbox to production, button now opens it's own popup window.  Thank you Michael!
Abby HouserAbby Houser
Hi there!  I keep getting the following error message and can't figure out why.  I use Enterprise Edition and am trying to create this to my accounts page.  Any help is appreciated!

User-added image
Mark SmithMark Smith
Great tips. Does anyone know how to display a google streetview instead?
Ken KoellnerKen Koellner
Any idea how well this would work within salesforce1 (SF1)?

Or if there's a better way to do it in SF1?
Peter GutmannPeter Gutmann
The "Salesforce1 Mobile Workbook" has very clear instructions on how to include this functionality. I found it on Meetup here: http://files.meetup.com/9288402/Salesforce1%20Mobile%20Workbook.pdf
Ken KoellnerKen Koellner
I've seen the warehouse map VF page example in the workbook but isn't that a different situation?  Or maybe I'm looking at a different part of the manual than you intended.

I guess what I'm asking is how that page works when embedded in a page layout that is then viewed in SF1.
Ken KoellnerKen Koellner
For example, an example of an issue with the code in this thread and SF1 is that it contains an apex:pageBlock tag and from what I've read of some of the mobile/SF1 documentation, it doesn't recommend using that tag.
Manjunath VManjunath V
I am not getting map on vf page.
Genise ChristiansonGenise Christianson
I just tried using this code on our sandbox and I keep getting an error message "Oops! "s address could not be found, please make sure the address is corrrect".  I did apphend the https to the code but I still keep getting the error.

Is it possible I am missing something?  I also added this to my layout and nothing is showing up at all, not even a empty box or a error message.

Any help is appreciated.

<apex:page standardController="Account">
<apex:pageBlock >
<head>

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

$(document).ready(function() {

  var myOptions = {
    zoom: 17,
    mapTypeId: google.maps.MapTypeId.HYBRID,
    mapTypeControl: true
  };

  var map;
  var marker;

  var geocoder = new google.maps.Geocoder();
  var address = "{!Account.BillingStreet}, " + "{!Account.BillingCity}, " + "{!Account.BillingPostalcode}";

  var infowindow = new google.maps.InfoWindow({
    content: "<b>{!Account.Name}</b>"
  });

  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' : '60px'});
      $('#map').html("Oops! {!Account.Name}'s 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:200px;
  background:transparent;
}
</style>

</head>

<body>
<div id="map"></div>
</body>
</apex:pageBlock>
</apex:page>
Manjunath VManjunath V
Hi,Genise Christianson. Pass the record id like below then you will get.

https://c.ap1.visual.force.com/apex/GoogleMapIntegration?id=0019000000ukJ3W

Now i got....Thanks All.
John HillstromJohn Hillstrom
Great code and I appreciate the questions and answers (like the scrollwheel: false tip).  One more javascript question, if you collapse the section and then re-expand it (using the arrow), the address point goes from centered to the left side of the map.  What do we need to do to re-center when expanding the section?
kiran nagarajukiran nagaraju
iam getting a blank page 
can one help me?

Andrew WestonAndrew Weston
I think the easiest thing to do is get an app. GeoTarget is $20 a month, In your page layouts, you can add their google map to records. Not only is it easier, you also have access to all their features which are amazing. Other apps like it cost far more. Our company found them a few months ago and absolutely love it!
Eric PozilEric Pozil

This worked great for me on standard objects, however, I can't get it to work in a custom object with custom address fields (since, there isn't a custom field type of address).  Can you tell what might be wrong with the APEX in this Visualforce page?

I'm not getting any errors, the problem is that the Google map doesn't show in the custom object section as a reference to a Visualforce page.  It is a blank screen.

<apex:page standardController="Property__c">

 

<head>

 

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

<script type="text/javascript" src="https://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 = "{Property__c.Property_Street__c}, " + "{!Property__c.Property_City__c}, " + "{!Property__c.Property_Zip__c};

 

  var infowindow = new google.maps.InfoWindow({

    content: "<b>{!Property__c.Name}</b>"

  });

 

  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: "{!Property__c.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! {!Property__c.Name}'s 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>

 

 

John HillstromJohn Hillstrom
@Eric Pozil - looks like you forgot the closing quote on the zip-code portion of your address.  It should probably be:
+ "{!Property__c.Property_Zip__c}";
Eric PozilEric Pozil
Thanks John - great catch.
Amjad OmarAmjad Omar
Few things to pay attention to when using this code for the first time:

1 - Make sure you use "https" instead of "http" for the two URLs beloe:

<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">

2 - The fields mentioned below by Dan stone are custom fields to his org, so make sure you create the same custom fields with the same naming or replace them with your standard fields as shown below:


Custom:
var address = "{!Account.Project_Street_Address__c}, " + "{!Account.Project_City__c}, " + "{!Account.Project_Zipcode__c}";

Standard:
var address = "{!Account.BillingStreet}, " + "{!Account.BillingCity}, " + "{!Account.BillingPostalcode}";


3 - Some people prefer the map to be zoomed out instead of zoomed in, you can edit this setting by changing the value of the field "zoom" in the below code (In my case I changed it to 5)

var myOptions = {
    zoom: 20,
    mapTypeId: google.maps.MapTypeId.HYBRID,
    mapTypeControl: true
  }


4 - You can change the default type of map that shows to any of the following values:

MapTypeId.ROADMAP
MapTypeId.SATELLITE
MapTypeId.TERRAIN

instead of "MapTypeId.HYBRID" that is being used in our example included in the below code (In the below example I replaced MapTypeId.HYBRID to MapTypeId.ROADMAP

var myOptions = {
    zoom: 4,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: true
  }
John HillstromJohn Hillstrom
@Amjad - great tips.  Now do you know how to prevent the map from getting un-centered if you expand and collapse the salesforce section it's in?
Josh HarshJosh Harsh
What is you had a related record and you wanted to show the distance between the account and related record? Would that be possible?
Amjad OmarAmjad Omar
John Hillstrom, 

I am not running into the same problem you are referring to, which is the un-centering of the map once the map section is expanded or collapsed.

Anyone else other than John running into the same problem?

Ravi KiranRavi Kiran
Thanks Dan for sharing this code. It works great even on custom object. 

Is there any way to take this code step further to show all the accounts/leads neary by to the opened account/lead record?
Dan StoneDan Stone
Ravi, the best way to do something like that is to get an AppExchange mapping package: https://appexchange.salesforce.com/results?keywords=map
Vinod AdminVinod Admin
Hi,
every one Dan Stone given such a good code to everyone for that thank you very much Dan. Some of the friends are getting empty map on their accounts for this we need to do 2 things first one is change Http to Https and second one it is not displaying for standard records because they are created address in one field only address field only so you can edit the address and enter address like 
Street = City County Building, Rm106A, 210 Martin Luther King Jr Blvd
City = Madison
State = WI
Zip = 53703
Country = USA
Then see the magic!
It'll work fine. 
Indrasen NeelamIndrasen Neelam
Hi All,

I am still getting blank page in my Account detail page. The Shipping address that in my account page is: 

                City County Building, Rm106A, 210 Martin Luther King Jr Blvd , Madison, WI 53703 USA
fyi - I am using developer edition. 

Please review the code.    Any help is higly appreciated.

Thanks,
Indy.



<apex:page standardController="Account">
<apex:pageBlock >
<head>

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

$(document).ready(function() {
 
  var myOptions = {
    zoom: 20,
    mapTypeId: google.maps.MapTypeId.HYBRID,
    mapTypeControl: true
  }
 
  var map;
  var marker;
 
  var geocoder = new google.maps.Geocoder();
  var address = "{!JSENCODE(Account.ShippingStreet)}, " + "{!Account.ShippingCity}, " + "{!Account.ShippingPostalcode}";

  var infowindow = new google.maps.InfoWindow({
    content: "<b>{!Account.Name}</b>"
  });

  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 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:500px;
  background:transparent;
}
</style>

</head>

<body>
<div id="map"></div>
</body>
</apex:pageBlock>
</apex:page>
Lucas LopesLucas Lopes
i change de http to https but its still blank to me :( any suggestion?
Chris UttleyChris Uttley
I have a formula field that builds the following string from shipping address:

https://www.google.com/maps/preview?q=#30 County Road 8,+Espanola,+NM,+United States,+87532

But when clicked, it doesnt show the address on the map....just a map of USA.

The formula is:

HYPERLINK("https://maps.google.com/maps?q=" &  ShippingStreet & ',+' &  ShippingCity & ',+' &  ShippingState & ',+' &   ShippingCountry & ',+' &  ShippingPostalCode,"Click for Map")

Any idea why this doesnt work?
Matt AveryMatt Avery
If you take the pound sign off of the 30 County Road 8, it appears to work fine. Tested by just punching that address into a browser. Got nothing with the #. Took off # and it zoomed right in to Espanola NM.
Aaron HernandezAaron Hernandez
Thanks for this thread.  It was very helpful.
Shana TilliesShana Tillies
Aaron your right this thread is very useful. Thanks all
Pim UijttewaalPim Uijttewaal
Looks great! Now looking for a way to show all accounts on the map. Any thoughts on this? 
David PrestonDavid Preston
test
Ben MervenBen Merven
I use GPS coordinates to place the pin, and I was having a problem earlier: the pin in the SF map was slightly off compared to when I pasted the same coordinates into google maps in the browser.

I've just figured out why. It seems the map in SF always want to snap the pin to the nearest road. See below:

Coordinates pasted into Google Maps (in the brower):
Coordinates in Google Maps

Coordinates displayed on the map in Salesforce:
Salesforce Map of same coordinates

Has anyone run into the same problem? Is there something to change in the code that will fix this?
Thanks
George KirkGeorge Kirk
Thanks this helped me 2 :D
Adriana SeijasAdriana Seijas
Hi all,

I am a new admin to SF and I am trying to learn as much as I can, I did try this code for the google map code and no errors when saving it however, I keep getting the Oops" addres could not be found, please make sure the address is correct.
What do I do now?
I did have to add this to the appropiate account page layouts correct?
Thanks, Adri
Adriana SeijasAdriana Seijas
I am very excited, I am new to SF and I am not a developer but I was able to make this work. thank you all for the very helpful imput and advice.
I love this feature.
Marc OsornoMarc Osorno
I attempted this in my sandbox and this worked just fine.  Good thread
Himanshu MehtaHimanshu Mehta
Hi Dan , How can we load both Billing and Shipping address, also i need to find difference between two address. Thanks in advance!!!
Bogdan PascuBogdan Pascu
Hi Dan,

Can you please help me with the code:
 We are trying to use the code to generate a map on an object called Location where we are using only latitude and longitude coordinates. Can you please tell me how it needs to be done to work.

Many thanks
yad jayanthyad jayanth
Google Maps has come out with the Embed API which lets you iframe a google map, just referencing the URL!! All you have to do is build a visualforce page with an iframe, pass in your records address as parameters, and voila!



<apex:page standardController="Account" extensions="MapController">
 
<iframe width="1200" height="450" frameborder="0" style="border:0"
  src="https://www.google.com/maps/embed/v1/place?key=YourKeyHere
  &q={!Account.Address__c}">
</iframe>
 
</apex:page>


The google maps api's are a lot of fun and have evolved a lot. The embedded method is by far the easiest and most manageable way to accomplish mapping a single address from a record in its detail page. There are a variety of parameters you can pass into the url in addition to just a single address. Please see documentation here:


https://developers.google.com/maps/documentation/embed/

If you need a fully configurable solution or have a complex set of needs, the Javascript API is the way to go (as detailed in other answers).

Here's a blog post that outlines some features that can also be used (with code samples) : 
http://blog.crmscience.com/2014/09/lab-coat-lesson-google-maps-api.html

Happy coding!
yad
Chris EggersChris Eggers
I have inserted the code into the Visualforce Markup as shown below but I am very new to this so I guess I am just a little confused.  Once I enter this code and save should it just show a map on every account page?


<apex:page standardController="Account"> <apex:pageBlock > <head> <script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var myOptions = { zoom: 4, mapTypeId: google.maps.MapTypeId.SATELLITE, mapTypeControl: true } var map; var marker; var geocoder = new google.maps.Geocoder(); var address = "{!Account.BillingStreet}, " + "{!Account.BillingCity}, " + "{!Account.BillingPostalcode}"; var infowindow = new google.maps.InfoWindow({ content: "<b>{!Account.Name}</b>" }); 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 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:500px; background:transparent; } </style> </head> <body> <div id="map"></div> </body> </apex:pageBlock> </apex:page>

Thanks for any assistance.
Louis AndersonLouis Anderson
So i am trying to accomplish exactly what this blog shows how to program 
http://blog.crmscience.com/2014/09/lab-coat-lesson-google-maps-api.html

can anyone please create the code i need to copy and paste i have no experience in coding or programing. I just want to add a google map that shows the route from my companies location to the accounts or contacts listed addresss. Any help is greatly appreciated thank you!
Adam LeeAdam Lee
Not sure if this has been posted but this guide will help you configure the whole layout like taking off the zoom bar, the streetview person etc. https://developers.google.com/maps/documentation/javascript/controls
priya burghatepriya burghate
Thank you so much @Dan its really working....:-)
Kelly SummersKelly Summers
great solution, is there a way to display the map on the contact page layout with the billing address from the account?
Kim DuncanKim Duncan
Thank you all for the initial code, the https fix, the centering code and zooming advice (I used 15, which was perfect for us)!!!  I was able to get this to work with my custom address fields after I determined I needed to use the API Name and realized there were TWO underscores before the c ("__c") at the end of it.

I had been trying to find a fix for breaking the Google Maps link once I used custom address fields. This works so well.
 
crenie prabakarancrenie prabakaran
Hi, I created a vf page using the code above, but when i use ?id=xxxx, I am getting a blank page.

Please help
Clarity TIBCOClarity TIBCO
You can try TIBCO Clarity for address cleansing. TIBCO Clarity enterprise edition support both TIBCO Geo Analytics and Google Maps as services.

TIBCO Clarity is the data cleaning and standardization component of the TIBCO Software System. It serves as a single solution for business users to handle massive messy data across various sources,  applications and systems, such as database, cloud storage, TIBCO Jaspersoft, Spotfire, ActiveSpaces,  MDM, Marketo and Salesforce. TIBCO® Clarity makes it easy for business users to profile, validate, dedup, address cleansing, standardize, transform, and visualize data so that trends can be identified and smart decisions can be made quickly. TIBCO Clarity provides both on cloud version and enterprise edition version.

TIBCO Clarity Overview/features:
https://clarity.cloud.tibco.com/landing/feature-summary.html

TIBCO Clarity over 40 demo videos(Watch me!):
https://clarity.cloud.tibco.com/landing/tutorial.html
 
Reshmi SmijuReshmi Smiju
HI,

This is such great post. Thank you Dan for the wonderful initiative . :)
However, I am not getting the result, as expected. Only getting a blank space. I have changed the http address to https like following.

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

User-added image

What could be the reason for this.. Since its a bot urgent, pls respond positively. HIghly appreciated.
Awaiting for the response.
Thanks
Karen ReffittKaren Reffitt
Thanks for this Dan!  We have construction project data imported into a custom object and this works perfectly to allow our reps to see the jobsite! Much appreciated. 
Taylor HetheringtonTaylor Hetherington

@anyone
I need the data i have in Salesforce about clients in certain regions to show up on a map, in salesforce.  

I have regional managers who manage multiple people at different locations.  I need to see all the regional managers and the people they manage, on the map, at the same time.  Will Dan's answer work for that????

Thank you to anyone who can help!

Terry MillerTerry Miller
@Taylor, take a look on AppExchange; there are several options that address where you're looking for.  eMaps from Vision-E  is one that I like.
Dan StoneDan Stone
Also check out MapAnything in the AppExchange: https://appexchange.salesforce.com/listingDetail?listingId=a0N3000000586bhEAA
Sascha DeinertSascha Deinert
Cool post, but how can extend the code to show me a map with all our accounts.
Is that possible?
Taylor HetheringtonTaylor Hetherington
@Terry Miller and @Dan Stone Is there a free version of any of those apps that you mentioned
Terry MillerTerry Miller
@Taylor Hetheringon nothing free that I'm aware of
Angela Mullen-SmithAngela Mullen-Smith
I am feeling really stupid but I cannot get this to work

<apex:page standardController="Account">
<apex:pageBlock >
<head>
 
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
 
$(document).ready(function() {
 
  var myOptions = {
    zoom: 20,
    mapTypeId: google.maps.MapTypeId.MAP,
    mapTypeControl: true
  }
 
  var map;
  var marker;
 
  var geocoder = new google.maps.Geocoder();
  var address =  "{!JSENCODE(Account.BillingStreet)}, " + "{!Account.BillingCity}, " + "{!Account.BillingPostalCode}, " + "{!Account.BillingCountry}";
 
  var infowindow = new google.maps.InfoWindow({
    content: "<b>{!Account.Name}</b>"
  });
 
  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 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:500px;
  background:transparent;
}
</style>
 
</head>
 
<body>
<div id="map"></div>
</body>
</apex:pageBlock>
</apex:page>
Angela Mullen-SmithAngela Mullen-Smith
Can anyone see what I've done wrong - a box appears on the page but no details


 
Dan StoneDan Stone
Your code works!  Make sure you're adding the VisualForce page to an Account page layout and then make sure the account you're looking at has the Billing Address populated (I ran into that issue myself just now). Let us know if that works.
Angela Mullen-SmithAngela Mullen-Smith
Yes thank you - Once I clicked on the box, the map appeared. Thank you for time for reply to my plea for help
Swapnil PatneSwapnil Patne
@Dan Stone.. thank you for this post, really very helpful! Managed to get it working with https but the only thing that is missing is marker. For some reasons it doesn't show up. Haven't change anything on the code except "zoom = 18" .. could you help me with marker please?

Many thanks,
Swapnil
David RobertsDavid Roberts
Has anyone succesfully completed the "Building a Mapping Application for iPhone" example? (https://developer.salesforce.com/docs/atlas.en-us.200.0.pages.meta/pages/pages_mobile_example.htm)
I get the list of accounts but no map. Controller test works fine but I don't know how to find out why the map isn't appearing.
Chris LanceChris Lance
After having this solution sucessfully running on our Account Page since February 2014 I noticed today that it'll render the map for a moment, but then displays the following error:

"Oops!  Something went wrong.  
This page didn't load Google Maps correctly.  See the JavaScript console for technical details."


Search results for this error returned an article that indicates this might be because Google Maps has started requiring an API key as of last year... https://churchthemes.com/page-didnt-load-google-maps-correctly

Curious if anyone else is seeing this issue now?
David RobertsDavid Roberts
Yes. Also get it with the App Store Map Plotter for Extentia_SIM.
Kim MoutesKim Moutes
Glad to know someone else is having this issue today. Ours has been successfully running since June of 2014. 
Kim DuncanKim Duncan
Ours is down today, as well. Kimberly Duncan Sales Support Coordinator, Sales & Development 972-420-7466 Office 800-727-2407 Toll Free 972-420-8383 Fax Kimberly.Duncan@horizonhealth.com www.HorizonHealth.com [Horizon Logo]
Chris LanceChris Lance
I'm just a lowly admin, so I'll have to ask one of my devs to take a look at this when they get a chance (or if there's a JS Developer on here that would be great too).  If it is the key issue as I suspect it appears there's a free plan that will provision a key that allows for 25k calls/day - https://developers.google.com/maps/documentation/javascript/ - I assume this would be plenty of calls for most users.

"Web - Google Maps JavaScript API:  Free up to 25,000 map loads per day"
Chris LanceChris Lance
Confirmed, you do indeed need to pass an API key as part of the request to Google now.  Here's how I fixed this:
  1. If you already have a developer Gmail login for your company, maybe use that.  Otherwise create a new one.
  2. After logging into Gmail go to https://developers.google.com/maps/documentation/javascript/ and click the Get a Key button - per the documentation this will be a free key that allows up to 25k calls a day.
  3. From the Salesforce VisualForce page where you've saved the code for this map, you need to update the two lines to include the key you generated (replacing "[KEYGOESHERE]" with the actual key. I learned this after reviewing the "hello world" documentation found here - https://developers.google.com/maps/documentation/javascript/tutorial):
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=[KEYGOESHERE]&sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js?key=[KEYGOESHERE]"></script>



That's it, my maps are up and running again... at least for the first 25k account pages views/day anyhow.
 
Kim MoutesKim Moutes
Worked great! Thank you @Chris Lance. 
Michael SchellMichael Schell
@Chris Lance....you're awesome bud. Thank you!
Shrijeet JoshiShrijeet Joshi
@dan Hi. I'm using your code for displaying a map(Account) inside a tab on my VF page. When i click on the tab to look at the map,the tab opens up and the map is shown. However after this i cannot navigate to any other tab as they dont respond when clicked upon. Please help me out! Cheers! 
Shraddha TirthaliShraddha Tirthali
@David Roberts, Google recently changed the parameters of their API, which has affected the Map Plotter geocoding process. We have released a patch that fixes the problems but you now need to turn on the Google Maps JavaScript API and the Google Places API Web Service (from the same place you turned on the Geocoding API) in order for Map Plotter to function correctly. 

Thanks for using the Map Plotter (https://appexchange.salesforce.com/listingDetail?listingId=a0N3000000B5P9CEAV) – we always appreciate the feedback!

For a small fee, you can use the power of Map Plotter Premium (https://appexchange.salesforce.com/listingDetail?listingId=a0N3A00000E1hEiUAJ) and visualize your data on the map.
David RobertsDavid Roberts
Hi Shraddha, Many thanks for your reply. Please tell me where I turn these on for MapPlotter. I have done so for our company Google API so calls my own functions make now work. However, the installed package MapPlotter still fails. Can you assist? Many thanks, Dave Roberts.
Shraddha TirthaliShraddha Tirthali
@David Roberts, 

We have recently pushed a patch(Version 1.11.2) with the fix for the issue to all our customers.
If the version of your Map Plotter installed does not match 1.11.2, you can upgrade to this new version by visiting the Map Plotter page on AppExchange and clicking 'Get It Now'.

Also, you will need to activate 3 Google APIs that Map Plotter requires for rendering the map, geocoding addresses, and searching nearby places. Please follow these steps to activate the APIs:
  • In Google console, Go to the Library tab in the left pane
  • Under Google Maps APIs, click More
  • Select 'Google Maps Geocoding APIs'
  • Click Enable to activate it
  • Similarly, activate the 'Google Maps JavaScript API' and 'Google Places API Web Service' from Library > Google Maps APIs
Once this is done, you can continue using Map Plotter as before.
David RobertsDavid Roberts
Many thanks Shraddha, The upgrade has fixed the issue. I couldn’t see the libraries section you describe but I was presented with a page about the API key. Pressing Save made it work. (I added my own weather key but don’t know if that has done anything yet). Great app. Thanks again. Dave.
Peter PremierPeter Premier

Hi everyone, thanks so much for this great post and conversation! 

I'm just getting started on Visualforce and like many of you, my map on the Account page doesn't display anything.

This is the code that I use at the moment:

<apex:page standardController="Account">
<apex:pageBlock >
<head>
 
<script type="text/javascript" src="httpss://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="httpss://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> 
<script type="text/javascript"> 
 
$(document).ready(function() {
  
  var myOptions = {
    zoom: 5,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: true
  }
  
  var map;
  var marker;
  
  var geocoder = new google.maps.Geocoder();
  var address = "{!JSENCODE(Account.Priority_Address__c)}, " + "{!Account.Priority_City_Location__c}, " + "{!Account.Priority_Postal_Code__c}";
  
  var infowindow = new google.maps.InfoWindow({
    content: "<b>{!Account.Name}</b>"
  });
 
  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 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:500px;
  background:transparent;
}
</style>
 
</head>
 
<body>
<div id="map"></div> 
</body> 
</apex:pageBlock>
</apex:page>


I already tried a few tweaks and applied your recommendations, but still all I get is this:

User-added image


Could anyone please advise me on this?

Thanks in advance!

David RobertsDavid Roberts
Looks like you're using Lightning in which case it gets confused - something to do with frames. There are threads about this but the alternative is to create a component. There's a good Trailhead about this.
It's on my "ToDo" list to convert my own version.
Peter PremierPeter Premier
Thanks for the prompt feedback David! Does this mean, if I want it to work, I don't need to change the code, but actually disable Lightning?
David RobertsDavid Roberts
Switch to Classic and see if it works.
If it is still blank then that isn't the issue.
Peter PremierPeter Premier
Hi David, I'm currently on the Classic UI, but same issue occurs.
David RobertsDavid Roberts
Ahh. Then the problem is elsewhere. Can’t look right now. May get time later.
Chris LanceChris Lance
Moritz and David, just checked to confirm the map works fine in in my org for Lightning and Classic.

Moritz, you have an extra S in your "httpss" links at the top.  If that doesn't solve the issue, see my previous comments from February 28, 2014 about wrapping the address in JSENCODE.  

Also as of earlier this year you need to include an API key from Google to use this solution, which you can get for free  from Google for up to 25,000 map loads per day (see my previous comments from February 17, 2017 on this)
Victor BarrosoVictor Barroso
Is there a way to make the map open in a new window/tab to Google Maps? Much like it does with the standard interface, but I'd like to maintain the interactive part as well.
Ashley LucasAshley Lucas
I am using the following code but my map is blank. Please help?

<apex:page standardController="Account"> <apex:pageBlock > <head> <script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyCxcLhv-Ih2eBWuEWN0o0sEES9LToCpzz0=false"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js?key=AIzaSyCxcLhv-Ih2eBWuEWN0o0sEES9LToCpzz0"></script> <script type="text/javascript"> $(document).ready(function() { var myOptions = { zoom: 20, mapTypeId: google.maps.MapTypeId.MAP, mapTypeControl: true } var map; var marker; var geocoder = new google.maps.Geocoder(); var address = "{!JSENCODE(Account.Bank_Address__c)}, " + "{!Account.Bank_City__c}, " + "{!Account.Bank_State__c}, " + "{!Account.Bank_Zip_Code__c}, " + "{!Account.Bank_Country__c}"; var infowindow = new google.maps.InfoWindow({ content: "<b>{!Account.Name}</b>" }); 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) map.setCenter(results[0].geometry.location); //center map map.setCenter(results[0].geometry.location); map.panBy(0,200); //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 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:500px; background:transparent; } </style> </head> <body> <div id="map"></div> </body> </apex:pageBlock> </apex:page>
Shraddha TirthaliShraddha Tirthali
Hi Ashley,

You seem to have missed initializing the map in the code. Also, the API is loaded as typescript. Another observation is, the script should be after the body..
What is your mapping requirement? Let me know so that I can help you more..

For now, this code should work,
<apex:page standardController="Account">
<apex:pageBlock>
<head>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCxcLhv-Ih2eBWuEWN0o0sEES9LToCpzz0&callback=initMap">
</script>
<style>
#map {
font-family: Arial;
font-size: 12px;
line-height: normal !important;
height: 500px;
background: transparent;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 20,
center: {
lat: -34.397,
lng: 150.644
}
});
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow;
var address = "India"; //fetch Salesforce address in here
geocodeAddress(geocoder, map, address, infowindow); //This will get the lat-lag and plot on the map
}
function geocodeAddress(geocoder, resultsMap, address, infowindow) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
infowindow.setContent(address);
infowindow.open(map, marker)
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
</body>
</apex:pageBlock>
</apex:page>

Hope this helps!! :)
Ashley LucasAshley Lucas
Getting the following error message...

Error: Bank_Map line 4, column 15: Attribute name "async" associated with an element type "script" must be followed by the ' = ' character
Error: Attribute name "async" associated with an element type "script" must be followed by the ' = ' character.
Chris UttleyChris Uttley
I added the map to my Account page about 3 years ago and it has functioned well. However, over the past few months, I notice that when I try and use my mouse wheel over the map to scroll the map in and out, the entire Account page now scrolls up and down instead of the map zooming in and out. 
Is there something that has changed or something I have to change to allow zooming within the map?
This is in Salesforce Classic.
All help appreciated!
Terry YangTerry Yang
hi Ashley, I got the same error as you .

just only change the line 4 , writting like this --   <script async="defer" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCxcLhv-Ih2eBWuEWN0o0sEES9LToCpzz0&callback=initMap">

then the problem will be cleared.
 
Angela Mullen-SmithAngela Mullen-Smith
I have used this code to view an Individual Account - but how do I display all Accounts via 1 Visualforce page
Chris UttleyChris Uttley
I received an email from Google Maps Platform over the weekend. It appears that Google will now be charging for use of their maps API if you exceed theire free usage threshold. It also appears that every google maps user (not Salesforce user)  MUST create a billing account to use the API.
If anyone has any further insight, please let me know!

"Hi,
Today we are announcing important changes, including our new name - Google Maps Platform, a simplified product structure, pay as you go pricing for all, and more. Please take a few minutes to review the announcement to familiarize yourself with the upcoming changes.
We would like to highlight a few updates that may impact your implementation. Beginning June 11th, we are launching our new pricing plan and providing all users access to support. We’ll continue to offer a free tier — all developers will receive $200 of free monthly usage of our core products.
In addition, this change will require you to enable billing and associate it with all of your Google Maps Platform projects. Creating a billing account helps us better understand your usage so we can continue developing helpful products. It also allows you to scale easily with less downtime and fewer performance issues if your product grows beyond the $200 of free monthly usage. For additional visibility and control you can set daily quotas or billing alerts.
How does this affect your current projects?
Project: My Project (XXXXXXXXXXXX)
Based on your project usage over the last 3 months and our new pricing plan, we estimate that your new cost will be less than $200 a month and will be covered by our $200 monthly free credit. This estimate does not include usage from other projects or keyless implementations.
We want to support you along the way. Please read our Guide for Existing Users to understand how these changes may impact your account and what steps you need to take.
Thank you for using Google Maps Platform."
Erin GilbertErin Gilbert
Thank you for posting this solution! This is totally changing the way we scheduled appointments.

When I applied it, I ran into the same "Google is charging for this service" that @Chris Uttley ran into, but looked at the Google Maps Platform documentation (https://developers.google.com/maps/documentation/javascript/v2tov3) and was able to get around it.

Just have to update the code a little to include your API key like @Terry Yang suggested:

<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=INSERT API KEY HERE"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
NABIN THAPANABIN THAPA
Hi,
Newbie here, can anyone explain why this VF page won't show map. Where as for Account it works (standardcontroller="Account" & substitute mailing to billing). Thanks 

<apex:page standardController="Contact">
<head>
<script type="text/javascript" src="https://maps.google.com/maps/api/js??key=Google API Key"></script>
<script type="text/javascript" src="https://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 ="{!Contact.mailingStreet},{!Contact.mailingPostalCode}{!Contact.mailingCity}, {!Contact.mailingState},{!Contact.mailingCountry}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Contact.Name}</b><br>{!Contact.mailingStreet}<br>{!Contact.mailingCity}, {!Contact.mailingPostalCode}<br>{!Contact.mailingState}<br>{!Contact.mailingCountry}"
});

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: "{!Contact.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! {!Contact.Name}'s mailing 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>
shyam Sundarshyam Sundar
Can i use the same code on changing respective fields depends to my custom object .?????
Brian MacDonaldBrian MacDonald
For those following this thread in the future a common cause of a blank box instead of a map is a problem with the API key. Make sure that your Google Cloud Platform Credentials has an API key that is either unrestricted (not recommended) or has the Geocoding API and Maps Javascript API enabled.
Brian MacDonaldBrian MacDonald
A friendly reminder to everyone to take care when pasting your your code in threads like this when it contains API keys - it is an easy thing for someone else to copy your API key and run up charges on your account.
Murray MasonMurray Mason

Over 8 years later since the original post and I wonder if this is still working for any of you. I have tried the recommendations from this "" with no luck. I am still getting the blank screen on the record and in a preview.

I have a custom object called "Zip_Code__c" with the field "Name" populated with the Zip Code. My goal is to have a map for each record showing the outline of the Zip Code. When I search a Zip Code in Google Maps that is the result I get.

Below is the most recent code I have used. API Key of course was replaced for security.
Any help would be appreciated.
 

<apex:page sidebar="false" standardController="Zip_Code__c">
<apex:pageBlock >
<head>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=___API_Key_would_go_here___&sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js?key=___API_Key_would_go_here___"></script>
<script type="text/javascript"> 
 
$(document).ready(function() {
  
  var myOptions = {
    zoom: 20,
    mapTypeId: google.maps.MapTypeId.HYBRID,
    mapTypeControl: true
  }
  
  var map;
  var marker;
  
  var geocoder = new google.maps.Geocoder();
  // ENTER ADDRESS BELOW 
  var address = "{Zip_Code__c.Name}, " + "United States";
  
  var infowindow = new google.maps.InfoWindow({
    content: "<b>{!Zip_Code__c.Name}</b>"
  });
 
  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);
        
        
        //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! {!Zip_Code__c.Name} could not be found, please make sure the Zip Code 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:500px;
  background:transparent;
}
</style>
 
</head>
 
<body>
<div id="map"></div> 
</body> 
</apex:pageBlock>
</apex:page>
Brian MacDonaldBrian MacDonald
Hi Murray - everything looks good. Are you sure that your API key is authorized for the required service? (Geocoding and Javascript APIs)
Murray MasonMurray Mason

Brian, I just created a new API with Geocoding and Java and tried again. I am now getting the error message for incorect address.The Google API dashboard shows 5 attempts with 100% errors. I copied an address from Google Maps and entered it into the code and still get the address error.

Any thoughts?

var address = "1095 Avenue of the Americas, 6th Ave, New York, NY 10036, United States";
Brian MacDonaldBrian MacDonald
I put this VF page onto the Account layout and it works well with the following code: (I'm a little pressed for time today so can't look at yours in detail - sorry). I also tried it with a hard coded address of "300 Bloor Street East, Toronto, Ontario, Canada, M4W 3Y2" which also worked.

<apex:page standardController="Account">
<apex:pageBlock >
<head>

<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=<MY_KEY>&sensor=false"></script>
<script type="text/javascript" src="https://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.MAP,
    mapTypeControl: true
  }
 
  var map;
  var marker;
 
  var geocoder = new google.maps.Geocoder();
  var address = "{!Account.ShippingStreet}, " + "{!Account.ShippingCity}, " + "{!Account.ShippingPostalcode}";

  var infowindow = new google.maps.InfoWindow({
    content: "<b>{!Account.Name}</b>"
  });
 
  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);
        map.panBy(0,100);
        
        //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 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:500px;
  background:transparent;
}
</style>
 
</head>
 
<body>
<div id="map"></div>
</body>
</apex:pageBlock>
</apex:page>
Jerry YuJerry Yu
Brian,

I used your code and am getting a blank page.