Golang : Find location by IP address and display with Google Map
This tutorial is a follow up for the previous tutorial on how to detect a user location with HTML5 Geolocation. However, this time we will learn how to get a user longitude and latitude from a user's IP address with the GeoLite2 free database and display the location visually with Google Map.
First, let's get the required ingredients by :
go get github.com/oschwald/geoip2-golang
go get github.com/gorilla/mux
and
wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz
gunzip GeoLite2-City.mmdb.gz
Next, we define our template plus JQuery to handle user input and canvas to display Google map.
Filename :
asklocation.html
<html>
<head>
<title>IP to location Golang example</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 80%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<h1>IP to Location Golang example</h1>
<div>
<input type="text" placeholder="0.0.0.0" id="ajax_btn" value="">
<span>
<button id="ajax_btn_search" type="button">Search</button>
</span>
</div>
<script>
$(document).ready(function () {
$('#ajax_btn_search').click(function () {
ipAddress = $('#ajax_btn').val()
$.ajax({
url: 'returncoord',
type: 'post',
dataType: 'html',
data : { ajax_post_data: ipAddress},
success : function(data) {
$('#result').html(data);
//get the Lat and Long as JSON
var json = JSON.parse(data);
showMap(json["Lat"], json["Long"], ipAddress);
},
});
});
});
var map;
function showMap(latitude,longitude,ipaddress) {
var pos = new google.maps.LatLng(latitude,longitude);
var mapOptions = {
zoom: 5,
center: pos,
mapTypeId: google.maps.MapTypeId.ROADMAP,
content : 'Location found by IP Address'
};
var mapDiv = document.getElementById("map-canvas");
map = new google.maps.Map(mapDiv, mapOptions);
var title = ipaddress + " location";
addMarker(map, pos, title, "");
}
function addMarker(map, latlong, title, content) {
var markerOptions = {
position: latlong,
map: map,
title: title,
clickable: true
};
var marker = new google.maps.Marker(markerOptions);
}
</script>
<div id='result'></div>
<br>
<br>
<div id="map-canvas"></div>
</body>
</html>
Filename :
asklocation.go
package main
import (
"fmt"
"github.com/gorilla/mux"
"github.com/oschwald/geoip2-golang"
"html/template"
"net"
"net/http"
)
func home(w http.ResponseWriter, r *http.Request) {
var templates = template.Must(template.New("locateip").ParseFiles("asklocation.html"))
err := templates.ExecuteTemplate(w, "asklocation.html", nil)
if err != nil {
panic(err)
}
}
func returnLatLong(w http.ResponseWriter, r *http.Request) {
// not recommended to open the file each time per request
// we put it here for tutorial sake.
db, err := geoip2.Open("GeoLite2-City.mmdb")
if err != nil {
fmt.Println(err)
}
defer db.Close()
if r.Method == "POST" {
ipAddress := r.FormValue("ajax_post_data")
// If you are using strings that may be invalid, check that IP is not nil
// and a valid IP address -- see https://www.socketloop.com/tutorials/golang-validate-ip-address
if ipAddress != "" {
ip := net.ParseIP(ipAddress)
record, err := db.City(ip)
if err != nil {
fmt.Println(err)
}
fmt.Printf("Country name in English: %v\n", record.Country.Names["en"])
fmt.Printf("Coordinates: Lat(%v), Long(%v)\n", record.Location.Latitude, record.Location.Longitude)
w.Write([]byte(fmt.Sprintf("{\"Country\":\"%v\",\"Lat\": \"%v\",\"Long\":\"%v\"}", record.Country.Names["en"],record.Location.Latitude, record.Location.Longitude)))
}
}
}
func main() {
mux := mux.NewRouter()
mux.HandleFunc("/", home)
mux.HandleFunc("/returncoord", returnLatLong)
http.ListenAndServe(":8080", mux)
}
Run the asklocation.go
file, point your browser to
Put in an IP address and click on the search button.
Hope this helps and happy coding!
NOTE : The GeoLite2 free database at http://dev.maxmind.com/geoip/geoip2/geolite2/ is by MaxMind
References :
https://godoc.org/github.com/oschwald/geoip2-golang
https://github.com/oschwald/geoip2-golang
https://www.socketloop.com/tutorials/javascript-read-parse-json-data-from-http-response
See also : Golang : Detect user location with HTML5 geo-location
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
+15.4k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy
+12.9k Golang : Convert(cast) int to int64
+5.2k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+15.7k Golang : Generate universally unique identifier(UUID) example
+6.5k Golang : Humanize and Titleize functions
+5.2k Javascript : How to loop over and parse JSON data?
+39.7k Golang : Convert to io.ReadSeeker type
+12.2k Elastic Search : Return all records (higher than default 10)
+9.5k Golang : Load ASN1 encoded DSA public key PEM file example
+16.2k CodeIgniter/PHP : Create directory if does not exist example
+23.2k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+46k Golang : Encode image to base64 example