In this tutorial we are going to draw region boundary lines on google maps with our free Openmapapi , Google Maps and Django .

Requirements

  1. Requests ( library )
  2. Geo Location Enabled Google Map Api key

Installation

The easiest way is to install the libraries using pip:

pip install requests 

Now create your view to get coordinates and render to template

views.py

def boundary_polygon(request):

if request.POST:

location = request.POST.get('location')

key = 'Enter Your Google Key Here'
data = {"location": location, "g_key" : key }

coordinates = requests.post('http://theopenmap.herokuapp.com/api/boundries_with_location/',data).json()
return render(request,'map.html',{'coordinates':coordinates})


else:
return render(request,'map.html')
Add some css

<style>
#map {
height: 425px;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>


Add div & form into HTML

<div id=“map”></div>

<div align="center" style="margin-top: 2%;">
<form method="post">{% csrf_token %}
<input type="text" name="location">
<input type="submit">
</form>
</div>

Add Script Files

Also Add Google Map Key To Google Map Script Url

<script>
function initMap() {

var map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: {'lat': {{ coordinates.0.0 }}, 'lng': {{ coordinates.0.1 }} } ,
mapTypeId: 'terrain'

});

var BoundryCoordinates = [
{% for coordinate in coordinates %}
{'lat': {{ coordinate.0 }}, 'lng': {{ coordinate.1 }} },
{% endfor %}

];

var Boundry = new google.maps.Polyline({
path: BoundryCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});

Boundry.setMap(map);
}
</script>

<script async defer
src=
"https://maps.googleapis.com/maps/api/js?key=AddYourKeyHere&callback=initMap">
</script>

Result

API URL

http://theopenmap.herokuapp.com/api/boundries_with_location/