Golang : Detect user location with HTML5 geo-location
Problem :
You need to detect your visitor's location (i.e latitude and longitude) and display on Google map showing the visitor's current location. How to do that in Golang ?
Solution :
Use HTML5 Geolocation function to retrieve a visitor's current location. The code example below demonstrate how to load an external HTML/Javascript file, display map with the location and pass the latitude, longitude data back to the server.
NOTE : Need to allow pop-up in the browser for this example to work
to run the program, simple execute the command
>go run html5geolocation.go
and direct your browser to port 8080. such as www.example.com:8080
html5geolocation.go file:
package main
import (
"fmt"
"github.com/gorilla/mux"
"html/template"
"net/http"
)
func home(w http.ResponseWriter, r *http.Request) {
var templates = template.Must(template.New("geolocate").ParseFiles("getlocation.html"))
err := templates.ExecuteTemplate(w, "getlocation.html", nil)
if err != nil {
panic(err)
}
prompt := "Detecting your location. Please click 'Allow' button"
w.Write([]byte(prompt))
}
func location(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
lat := vars["lat"]
long := vars["long"]
w.Write([]byte(fmt.Sprintf("Lat is %s \n", lat)))
w.Write([]byte(fmt.Sprintf("Long is %s \n", long)))
fmt.Printf("Lat is %s and Long is %s \n", lat, long)
// if you want to get timezone from latitude and longitude
// checkout http://www.geonames.org/export/web-services.html#timezone
}
func main() {
mux := mux.NewRouter()
mux.HandleFunc("/", home)
mux.HandleFunc("/location/{lat}/{long}", location)
http.ListenAndServe(":8080", mux)
}
and getlocation.html
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see a blank space instead of the map, this
// is probably because you have denied permission for location sharing.
var map;
function initialize() {
var mapOptions = {
zoom: 6
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
// capture latitude and longtitude... pass back to backend
// this tutorial open a new window(pop-up) ...if you don't want to open new window, use AJAX to
// send data to backend
handleGeolocationData(position.coords.latitude,position.coords.longitude);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleGeolocationData(latitude, longitude){
// window.location = "/location/"+latitude+"/"+longitude;
var strWindowFeatures = "location=yes,height=570,width=520,scrollbars=yes,status=yes";
var URL = "http://socketloop.com:8080/location/"+latitude+"/"+longitude;
window.open(URL, "_blank", strWindowFeatures);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
References :
https://www.socketloop.com/references/golang-html-template-template-execute-function-example
https://www.socketloop.com/tutorials/golang-gorilla-mux-routing-example
https://developers.google.com/maps/documentation/javascript/examples/map-geolocation
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12.7k Python : Convert IPv6 address to decimal and back to IPv6
+11.5k Golang : GTK Input dialog box examples
+18.7k Golang : Read input from console line
+4.7k Golang : PGX CopyFrom to insert rows into Postgres database
+9.6k Golang : Function wrapper that takes arguments and return result example
+21.1k Golang : How to read float value from standard input ?
+19.5k Golang : Count JSON objects and convert to slice/array
+8.1k Useful methods to access blocked websites
+12k Golang : Display list of countries and ISO codes
+6.3k Golang : Totalize or add-up an array or slice example
+7.3k Gogland : Single File versus Go Application Run Configurations
+6.1k Golang : Detect face in uploaded photo like GPlus