ShowAll Questionssorted byDate Posted
Juan Spagnoli

# Convert from Decimal latitude/longitude to Degrees

Hi guys, with the new Geolocation's fields I had the need of create an apex class for converting decimal values to degree strings, like SFDC do with the coordinates.

I want to share the class with the community:

```public class GeolocationDecimalToDegreesConverter{
public static String convert(Decimal latitude, Decimal longitude){
return convertLatitud(latitude) + ' ' + convertLongitude(longitude);
}

public static String convertLatitud(Decimal latitude){
String result = '';
if(latitude != null){
String direction = 'N';
if(latitude < 0){
direction = 'S';
}
result = convert(latitude) + direction;
}
return result;
}

public static String convertLongitude(Decimal longitude){
String result = '';
if(longitude != null){
String direction = 'E';
if(longitude < 0){
direction = 'W';
}
result = convert(longitude) + direction;
}
return result;
}

private static String convert(Decimal d){
d = d.abs();

//degrees
Integer i = d.intValue();
String s = String.valueOf(i) + '°';

//minutes
d = d - i;
d = d * 60;
i = d.intValue();
s = s + String.valueOf(i) + '\'';

//seconds
d = d - i;
d = d * 60;
i = d.round().intValue();
s = s + String.valueOf(i) + '"';

return s;
}
}```

Test:

```@IsTest
public class TestGeolocationDecimalToDegreesConverter{
private static testmethod void test(){
Decimal latitude = -38.0168573067988;
Decimal longitude = -57.5689172744751;

String result = GeolocationDecimalToDegreesConverter.convert(latitude, longitude);
System.AssertEquals('38°1\'1"S 57°34\'8"W', result);
}
}```