function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ramk123Ramk123 

Populate longitude and latitude on custom object using Google API

How to populate logitude and latitude on custome object using Google API.
Any one please help on this? Thank you!
Best Answer chosen by Ramk123
Ramk123Ramk123
With the below code i can able to autopulate Latitude and Longtitude based address specified

{!REQUIRESCRIPT("https://maps-api-ssl.google.com/maps/api/js?v=3&sensor=false")} 
{!REQUIRESCRIPT("https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js")} 
{!REQUIRESCRIPT("../../soap/ajax/26.0/connection.js")} 

var address ='{!Apartment_Property__c.Address_Street__c}, ' + '{!Apartment_Property__c.City__c}, ' + '{!Apartment_Property__c.State__c}, ' + '{!Apartment_Property__c.Country__c}'; 

sforce.connection.sessionId = '{!$Api.Session_ID}'; 

var geocoder = new google.maps.Geocoder(); 
var geocoderRequest = { 
address: address 


geocoder.geocode(geocoderRequest, function(results, status){ 
if(status == google.maps.GeocoderStatus.OK) { 

var googleAddress = results[0].formatted_address; 
var lat = results[0].geometry.location.lat(); 
var lng = results[0].geometry.location.lng(); 
console.log('======googleAddress=====>' + googleAddress + '==== latitude ====>' + lat + '==== longitude ====>' + lng); 

// updating a Propertylocation record 
var PropertyTest = new sforce.SObject("Apartment_Property__c"); 
PropertyTest.id = "{!Apartment_Property__c.Id}"; 
PropertyTest.Geolocation__Latitude__s = lat; 
PropertyTest.Geolocation__Longitude__s = lng; 
sforce.connection.update([PropertyTest]); 
window.parent.location = "/"+PropertyTest.id;//to reload the window and show the updated values 


else if(status = google.maps.GeocoderStatus.ZERO_RESULTS) { 
//YOUR LOGIN 

else if(status = google.maps.GeocoderStatus.OVER_QUERY_LIMIT) { 
// YOUR LOGIC 

else if(status = google.maps.GeocoderStatus.INVALID_REQUEST) { 
// YOUR LOGIC 

});
 

All Answers

Raj VakatiRaj Vakati
Step 1 : Create a trigger that will call the apex callouts 
Step 2 : Create an apex class 
Here the endpoint URL that you need to use 

http://maps.google.com/maps/api/geocode/json?address=300+Collins+St,+Docklands,+VIC&sensor=false&components=country:AU
Please refer this link for same sample code

http://merfantz.com/blog/how-to-get-geolocation-in-salesforce-through-apex-class/

 
Ramk123Ramk123
Thanks for your quick response!

I have quick question on apex class, what is string value here, am getting error on this line String address = '';
Raj VakatiRaj Vakati
The address whihc you wanted to fetch the  latitude 
Ramk123Ramk123
I didn't get you, Let me explain you the issue once again. When i complie the Apex Callout am getting errors because of Address string is empty 
Error Message :

Error: Compile Error: Invalid identifier '’'. Apex identifiers must start with an ASCII letter (a-z or A-Z) followed by any number of ASCII letters (a-z or A-Z), digits (0 - 9), '$', '_'. at line 12 column 28

Apex Callout:
public class LocationCallouts {
@future(callout=true)
static public void newAccmethod(set<id> li){
for(Account a : [SELECT BillingCity,BillingCountry,BillingPostalCode,BillingState,BillingStreet FROM Account WHERE id =: li]){
String address = ''; 
if (a.BillingStreet != null)
address += a.BillingStreet +’, ‘; -->Error location is here 
if (a.BillingCity != null)
address += a.BillingCity +’, ‘;
if (a.BillingState != null)
address += a.BillingState +’ ‘;
if (a.BillingPostalCode != null)
address += a.BillingPostalCode +’, ‘;
if (a.BillingCountry != null)
address += a.BillingCountry;
address = EncodingUtil.urlEncode(address, ‘UTF-8’);
// build callout
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint(‘http://maps.googleapis.com/maps/api/geocode/json?address=’+address+’&sensor=false’);
req.setMethod(‘GET’);
req.setTimeout(5000);
try{
// callout
HttpResponse res = h.send(req);
// parse coordinates from response
JSONParser parser = JSON.createParser(res.getBody());
double lat = null;
double lon = null;
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == ‘location’)){
parser.nextToken(); // object start
while (parser.nextToken() != JSONToken.END_OBJECT){
String txt = parser.getText();
parser.nextToken();
if (txt == ‘lat’)
lat = parser.getDoubleValue();
else if (txt == ‘lng’)
lon = parser.getDoubleValue();
}
}
}
// update coordinates if we get back
if (lat != null){
system.debug(lat+’ ‘+lon);
a.Geo__Latitude__s = lat;
system.debug(a.Geo__Latitude__s+’a.Geo__Latitude__s’);
a.Geo__Longitude__s = lon;
system.debug(a.Geo__Longitude__s +’a.Geo__Longitude__s’);
update a;
}
}
catch (Exception e) {
system.debug(e);
}
}
}
}
Raj VakatiRaj Vakati
try this 
 
Apex Callout:
public class LocationCallouts {
@future(callout=true)
static public void newAccmethod(set<id> li){
for(Account a : [SELECT BillingCity,BillingCountry,BillingPostalCode,BillingState,BillingStreet FROM Account WHERE id =: li]){
String address = ''; 
if (a.BillingStreet != null)
address += a.BillingStreet +','; -->Error location is here 
if (a.BillingCity != null)
address += a.BillingCity +',';
if (a.BillingState != null)
address += a.BillingState +',';
if (a.BillingPostalCode != null)
address += a.BillingPostalCode +',';
if (a.BillingCountry != null)
address += a.BillingCountry;
// build callout
if(address!=null){
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('http://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false');
req.setMethod('GET');
req.setTimeout(5000);
try{
// callout
HttpResponse res = h.send(req);
// parse coordinates from response
JSONParser parser = JSON.createParser(res.getBody());
double lat = null;
double lon = null;
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'location')){
parser.nextToken(); // object start
while (parser.nextToken() != JSONToken.END_OBJECT){
String txt = parser.getText();
parser.nextToken();
if (txt == 'lat')
lat = parser.getDoubleValue();
else if (txt == 'lng')
lon = parser.getDoubleValue();
}
}
}
// update coordinates if we get back
if (lat != null){
system.debug(lat+' '+lon);
a.Geo__Latitude__s = lat;
system.debug(a.Geo__Latitude__s+'a.Geo__Latitude__s');
a.Geo__Longitude__s = lon;
system.debug(a.Geo__Longitude__s +'a.Geo__Longitude__s');
update a;
}
}
catch (Exception e) {
system.debug(e);
}
}
}
}
}

 
Ramk123Ramk123
With the below code i can able to autopulate Latitude and Longtitude based address specified

{!REQUIRESCRIPT("https://maps-api-ssl.google.com/maps/api/js?v=3&sensor=false")} 
{!REQUIRESCRIPT("https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js")} 
{!REQUIRESCRIPT("../../soap/ajax/26.0/connection.js")} 

var address ='{!Apartment_Property__c.Address_Street__c}, ' + '{!Apartment_Property__c.City__c}, ' + '{!Apartment_Property__c.State__c}, ' + '{!Apartment_Property__c.Country__c}'; 

sforce.connection.sessionId = '{!$Api.Session_ID}'; 

var geocoder = new google.maps.Geocoder(); 
var geocoderRequest = { 
address: address 


geocoder.geocode(geocoderRequest, function(results, status){ 
if(status == google.maps.GeocoderStatus.OK) { 

var googleAddress = results[0].formatted_address; 
var lat = results[0].geometry.location.lat(); 
var lng = results[0].geometry.location.lng(); 
console.log('======googleAddress=====>' + googleAddress + '==== latitude ====>' + lat + '==== longitude ====>' + lng); 

// updating a Propertylocation record 
var PropertyTest = new sforce.SObject("Apartment_Property__c"); 
PropertyTest.id = "{!Apartment_Property__c.Id}"; 
PropertyTest.Geolocation__Latitude__s = lat; 
PropertyTest.Geolocation__Longitude__s = lng; 
sforce.connection.update([PropertyTest]); 
window.parent.location = "/"+PropertyTest.id;//to reload the window and show the updated values 


else if(status = google.maps.GeocoderStatus.ZERO_RESULTS) { 
//YOUR LOGIN 

else if(status = google.maps.GeocoderStatus.OVER_QUERY_LIMIT) { 
// YOUR LOGIC 

else if(status = google.maps.GeocoderStatus.INVALID_REQUEST) { 
// YOUR LOGIC 

});
 
This was selected as the best answer
James Jacob 1James Jacob 1
I used MapBox api to get location and gps coordinates of a User. You can check here example of getting longitude and latitude using an API.
https://where-am-i.live