You need to sign in to do that
Don't have an account?
Sivasankari Muthu
How to get google map for current location without api key
Hi Everyone,
I want to get google map for current location viewing & longitude and latitude without api key.
google javascript api v3 js file Link
https://maps.googleapis.com/maps/api/js
Codes:
1.VF Code:
<apex:page sidebar="false" showheader="false" standardController="Account" extensions="FindNearby">
<!-- Include in Google's Maps API via JavaScript static resource -->
<apex:includeScript value="{!$Resource.googleMapsAPI}" />
<!-- Set this API key to fix JavaScript errors in production -->
<!--http://salesforcesolutions.blogspot.com/2013/01/integration-of-salesforcecom-and-google.html-->
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"> <!-- We try to get google mapy without API Key (Javascript V3) but i did not show the current location as well as longitude and latitude -->
<!-- src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAowmYdY3dZwoe4qI1I_X8Ry-UPepb5dpA&sensor=false"> previously we used API key to generate Google Map but the usage of API key is very limited(Only 4 times) -->
</script>
<!-- Setup the map to take up the whole window -->
<style>
html, body { height: 100%; }
.page-map, .ui-content, #map-canvas { width: 100%; height:100%; padding: 0; }
#map-canvas { height: min-height: 100%; }
</style>
<script>
function initialize() {
var lat, lon;
// If we can, get the position of the user via device geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
lat = position.coords.latitude;
lon = position.coords.longitude;
// Use Visualforce JavaScript Remoting to query for nearby accts
Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.FindNearby.getNearby}', lat, lon,
function(result, event){
if (event.status) {
console.log(result);
createMap(lat, lon, result);
} else if (event.type === 'exception') {
//exception case code
} else {
}
},
{escape: true}
);
});
} else {
// Set default values for map if the device doesn't have geolocation capabilities
/** Eindhoven **/
lat = 12.9172;
lon = 80.1929;
var result = [];
createMap(lat, lon, result);
}
}
function createMap(lat, lon, accts)
{
// Get the map div, and center the map at the proper geolocation
var currentPosition = new google.maps.LatLng(lat,lon);
var mapDiv = document.getElementById('map-canvas');
var map = new google.maps.Map(mapDiv, {
center: currentPosition,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADTYPE
});
// Set a marker for the current location
var positionMarker = new google.maps.Marker({
map: map,
position: currentPosition,
icon: 'http://maps.google.com/mapfiles/ms/micons/pink.png'
});
// Keep track of the map boundary that holds all markers
var mapBoundary = new google.maps.LatLngBounds();
mapBoundary.extend(currentPosition);
// Set markers on the map from the @RemoteAction results
var acct;
for(var i=0; i<accts.length;i++){
acct = accts[i];
console.log(accts[i]);
setupMarker();
}
// Resize map to neatly fit all of the markers
map.fitBounds(mapBoundary);
function setupMarker(){
var acctNavUrl;
// Determine if we are in Salesforce1 and set navigation link appropriately
try{
if(sforce.one){
acctNavUrl =
'javascript:sforce.one.navigateToSObject(\'' + acct.Id + '\')';
}
} catch(err) {
console.log(err);
acctNavUrl = '\\' + acct.Id;
}
var acctDetails =
'<a href="' + acctNavUrl + '">' +
acct.Name + '</a><br/>' +
acct.BillingStreet + '<br/>' +
acct.BillingCity + '<br/>' +
acct.Phone;
// Create the callout that will pop up on the marker
var infowindow = new google.maps.InfoWindow({
content: acctDetails
});
// Place the marker on the map
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(
acct.Location__Latitude__s,
acct.Location__Longitude__s)
});
mapBoundary.extend(marker.getPosition());
// Add the action to open up the panel when it's marker is clicked
google.maps.event.addListener(marker, 'click', function(){
infowindow.open(map, marker);
});
}
}
// Fire the initialize function when the window loads
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body style="font-family: Arial; border: 0 none;">
<!-- All content is rendered by the Google Maps code -->
<!-- This minimal HTML justs provide a target for GMaps to write to -->
<div id="map-canvas"></div>
</body>
</apex:page>
2.Apex Class --- FindNearby
global with sharing class FindNearby {
public FindNearby(ApexPages.StandardController sc){}
@RemoteAction
// Find Accounts nearest a geolocation
global static List<Account> getNearby(String lat, String lon) {
// If geolocation isn't set, use Eindhoven (or any other city)
// Put a default location latitue and longitude here, this could be where you are located the most
// and will only be used as a backup if the browser can not get your location details
if(lat == null || lon == null || lat.equals('') || lon.equals('')) {
lat = '51.096214';
lon = '3.683153';
}
// SOQL query to get the nearest accounts
//you can change km (kilometers) into mi (miles)
// < 20 means within a radius of 20 km or mi (you can change that)
//limit 25 shows 25 records (you can adapt that too if you want)
String queryString =
'SELECT Id, Name, Location__Longitude__s, Location__Latitude__s, ' +
'BillingStreet, Phone, BillingCity ' +
'FROM Account ' +
'WHERE DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'km\') < 20 ' +
'ORDER BY DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'km\') ' +
'LIMIT 25';
// Run and return the query results
return(database.Query(queryString));
}
}
3.Apex Trigger
// Trigger runs getLocation() on Accounts with no Geolocation
trigger SetGeolocation on Account (after insert, after update) {
for (Account a : trigger.new){
if(Trigger.isUpdate){
if(a.BillingStreet != Trigger.oldMap.get(a.id).BillingStreet || a.BillingCity != Trigger.oldMap.get(a.id).BillingCity || a.BillingPostalCode != Trigger.oldMap.get(a.id).BillingPostalCode){
LocationCallouts.getLocation(a.id);
}
}
if (a.Location__Latitude__s == null)
LocationCallouts.getLocation(a.id);
}
}
4.Apex Class
public class LocationCallouts {
@future (callout=true) // future method needed to run callouts from Triggers
static public void getLocation(id accountId){
// gather account info
Account a = [SELECT BillingCity,BillingCountry,BillingPostalCode,BillingState,BillingStreet FROM Account WHERE id =: accountId];
// create an address string
String address = '';
if (a.BillingStreet != null)
address += a.BillingStreet +', ';
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(6000);
try{
// callout
HttpResponse res = h.send(req);
System.debug(res.getBody());
// 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){
a.Location__Latitude__s = lat;
a.Location__Longitude__s = lon;
update a;
}
} catch (Exception e) {
}
}
}
Thanks in advance,
If anybody know please tell me.
Thanks and Regards,
Sivasankari.M
I want to get google map for current location viewing & longitude and latitude without api key.
google javascript api v3 js file Link
https://maps.googleapis.com/maps/api/js
Codes:
1.VF Code:
<apex:page sidebar="false" showheader="false" standardController="Account" extensions="FindNearby">
<!-- Include in Google's Maps API via JavaScript static resource -->
<apex:includeScript value="{!$Resource.googleMapsAPI}" />
<!-- Set this API key to fix JavaScript errors in production -->
<!--http://salesforcesolutions.blogspot.com/2013/01/integration-of-salesforcecom-and-google.html-->
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"> <!-- We try to get google mapy without API Key (Javascript V3) but i did not show the current location as well as longitude and latitude -->
<!-- src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAowmYdY3dZwoe4qI1I_X8Ry-UPepb5dpA&sensor=false"> previously we used API key to generate Google Map but the usage of API key is very limited(Only 4 times) -->
</script>
<!-- Setup the map to take up the whole window -->
<style>
html, body { height: 100%; }
.page-map, .ui-content, #map-canvas { width: 100%; height:100%; padding: 0; }
#map-canvas { height: min-height: 100%; }
</style>
<script>
function initialize() {
var lat, lon;
// If we can, get the position of the user via device geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
lat = position.coords.latitude;
lon = position.coords.longitude;
// Use Visualforce JavaScript Remoting to query for nearby accts
Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.FindNearby.getNearby}', lat, lon,
function(result, event){
if (event.status) {
console.log(result);
createMap(lat, lon, result);
} else if (event.type === 'exception') {
//exception case code
} else {
}
},
{escape: true}
);
});
} else {
// Set default values for map if the device doesn't have geolocation capabilities
/** Eindhoven **/
lat = 12.9172;
lon = 80.1929;
var result = [];
createMap(lat, lon, result);
}
}
function createMap(lat, lon, accts)
{
// Get the map div, and center the map at the proper geolocation
var currentPosition = new google.maps.LatLng(lat,lon);
var mapDiv = document.getElementById('map-canvas');
var map = new google.maps.Map(mapDiv, {
center: currentPosition,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADTYPE
});
// Set a marker for the current location
var positionMarker = new google.maps.Marker({
map: map,
position: currentPosition,
icon: 'http://maps.google.com/mapfiles/ms/micons/pink.png'
});
// Keep track of the map boundary that holds all markers
var mapBoundary = new google.maps.LatLngBounds();
mapBoundary.extend(currentPosition);
// Set markers on the map from the @RemoteAction results
var acct;
for(var i=0; i<accts.length;i++){
acct = accts[i];
console.log(accts[i]);
setupMarker();
}
// Resize map to neatly fit all of the markers
map.fitBounds(mapBoundary);
function setupMarker(){
var acctNavUrl;
// Determine if we are in Salesforce1 and set navigation link appropriately
try{
if(sforce.one){
acctNavUrl =
'javascript:sforce.one.navigateToSObject(\'' + acct.Id + '\')';
}
} catch(err) {
console.log(err);
acctNavUrl = '\\' + acct.Id;
}
var acctDetails =
'<a href="' + acctNavUrl + '">' +
acct.Name + '</a><br/>' +
acct.BillingStreet + '<br/>' +
acct.BillingCity + '<br/>' +
acct.Phone;
// Create the callout that will pop up on the marker
var infowindow = new google.maps.InfoWindow({
content: acctDetails
});
// Place the marker on the map
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(
acct.Location__Latitude__s,
acct.Location__Longitude__s)
});
mapBoundary.extend(marker.getPosition());
// Add the action to open up the panel when it's marker is clicked
google.maps.event.addListener(marker, 'click', function(){
infowindow.open(map, marker);
});
}
}
// Fire the initialize function when the window loads
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body style="font-family: Arial; border: 0 none;">
<!-- All content is rendered by the Google Maps code -->
<!-- This minimal HTML justs provide a target for GMaps to write to -->
<div id="map-canvas"></div>
</body>
</apex:page>
2.Apex Class --- FindNearby
global with sharing class FindNearby {
public FindNearby(ApexPages.StandardController sc){}
@RemoteAction
// Find Accounts nearest a geolocation
global static List<Account> getNearby(String lat, String lon) {
// If geolocation isn't set, use Eindhoven (or any other city)
// Put a default location latitue and longitude here, this could be where you are located the most
// and will only be used as a backup if the browser can not get your location details
if(lat == null || lon == null || lat.equals('') || lon.equals('')) {
lat = '51.096214';
lon = '3.683153';
}
// SOQL query to get the nearest accounts
//you can change km (kilometers) into mi (miles)
// < 20 means within a radius of 20 km or mi (you can change that)
//limit 25 shows 25 records (you can adapt that too if you want)
String queryString =
'SELECT Id, Name, Location__Longitude__s, Location__Latitude__s, ' +
'BillingStreet, Phone, BillingCity ' +
'FROM Account ' +
'WHERE DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'km\') < 20 ' +
'ORDER BY DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'km\') ' +
'LIMIT 25';
// Run and return the query results
return(database.Query(queryString));
}
}
3.Apex Trigger
// Trigger runs getLocation() on Accounts with no Geolocation
trigger SetGeolocation on Account (after insert, after update) {
for (Account a : trigger.new){
if(Trigger.isUpdate){
if(a.BillingStreet != Trigger.oldMap.get(a.id).BillingStreet || a.BillingCity != Trigger.oldMap.get(a.id).BillingCity || a.BillingPostalCode != Trigger.oldMap.get(a.id).BillingPostalCode){
LocationCallouts.getLocation(a.id);
}
}
if (a.Location__Latitude__s == null)
LocationCallouts.getLocation(a.id);
}
}
4.Apex Class
public class LocationCallouts {
@future (callout=true) // future method needed to run callouts from Triggers
static public void getLocation(id accountId){
// gather account info
Account a = [SELECT BillingCity,BillingCountry,BillingPostalCode,BillingState,BillingStreet FROM Account WHERE id =: accountId];
// create an address string
String address = '';
if (a.BillingStreet != null)
address += a.BillingStreet +', ';
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(6000);
try{
// callout
HttpResponse res = h.send(req);
System.debug(res.getBody());
// 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){
a.Location__Latitude__s = lat;
a.Location__Longitude__s = lon;
update a;
}
} catch (Exception e) {
}
}
}
Thanks in advance,
If anybody know please tell me.
Thanks and Regards,
Sivasankari.M
This link will help you for salesforce integrate with google map api..
http://webkul.com/blog/how-to-integrate-google-map-api-in-salesforce/
Thanks and Regards,
Nansi kela
All Answers
This link will help you for salesforce integrate with google map api..
http://webkul.com/blog/how-to-integrate-google-map-api-in-salesforce/
Thanks and Regards,
Nansi kela
Thank you for your reply
Its working..
how to get longitude and latitude for location without api key.
do you have any idea please tell me..
Thanks,
I am unable to autopopulate my address in lightning component.Please find the issue. Anyone please help me.