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.

IP address to location with Golang

First, let's get the required ingredients by :

go get github.com/oschwald/geoip2-golang

go get github.com/gorilla/mux


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


 <title>IP to location Golang example</title>
 <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
 <meta charset="utf-8">
 html, body, #map-canvas {
 height: 80%;
 margin: 0px;
 padding: 0px
 <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>



 <h1>IP to Location Golang example</h1>
 <input type="text" placeholder="" id="ajax_btn" value="">
 <button id="ajax_btn_search" type="button">Search</button>

 $(document).ready(function () { 
 $('#ajax_btn_search').click(function () {

 ipAddress = $('#ajax_btn').val()

 url: 'returncoord',
 type: 'post',
 dataType: 'html',
 data : { ajax_post_data: ipAddress},
 success : function(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); 

 <div id='result'></div>

 <div id="map-canvas"></div>


Filename : asklocation.go

 package main

 import (

 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 {


 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 {

 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.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 :8080 and you should be able to see an input field and search button.

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 :





  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.