Skip to content

Instantly share code, notes, and snippets.

@joshbirk
Created October 8, 2012 21:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save joshbirk/3855091 to your computer and use it in GitHub Desktop.
Save joshbirk/3855091 to your computer and use it in GitHub Desktop.
Geolocation
<apex:page StandardController="Contact" showHeader="true" sidebar="false">
<script>
var pos = {};
function success(position) {
pos = position.coords;
console.log(pos);
}
function error(msg) {
console.log(msg);
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
error('not supported');
}
function setPos() {
var inputs = document.getElementsByTagName('input');
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].id.indexOf('contactlat') >= 0) { inputs[x].value = pos.latitude; }
if(inputs[x].id.indexOf('contactlong') >= 0) { inputs[x].value = pos.longitude; }
}
}
</script>
<apex:form >
<apex:pageBlock>
<apex:pageBlockButtons>
<apex:commandButton action="{!quicksave}" value="Save"/>
<button onClick="setPos(); return false;" id="setPosBtn">Set Position</button>
</apex:pageBlockButtons>
<apex:pageBlockSection title="My Contact" columns="2">
<apex:inputField value="{!Contact.FirstName}" />
<apex:inputField value="{!Contact.LastName}" />
<apex:inputField value="{!Contact.Location__Latitude__s}" id="contactlat" />
<apex:inputField value="{!Contact.Location__Longitude__s}" id="contactlong" />
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
public with sharing class GeoContactController {
public GeoContactController() {
}
public GeoContactController(ApexPages.StandardController stdc) {
}
@RemoteAction
public static List<Contact> getNearbyContacts(Decimal clat, Decimal clong) {
String q = 'SELECT Name FROM Contact WHERE DISTANCE(Location__c, GEOLOCATION('+String.valueOf(clat)+','+String.valueOf(clong)+'), "mi") < 10';
List<Contact> contacts = Database.query(q);
return contacts;
}
}
@geosow
Copy link

geosow commented Jan 2, 2013

I was getting an error with the class above. I had to change line 13 to the following because I was getting errors with the double quotes:

String q = 'SELECT Name FROM Contact WHERE DISTANCE(Location__c, GEOLOCATION('+String.valueOf(clat)+','+String.valueOf(clong)+'), 'mi') < 10';

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment