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

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 :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 :

https://godoc.org/github.com/oschwald/geoip2-golang

https://github.com/oschwald/geoip2-golang

https://www.socketloop.com/tutorials/golang-jquery-ajax-post-data-to-server-and-send-data-back-to-client-example

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