[Fixed]-Fetch data from django and place on google maps using javascript

1👍

Lets say you have a model like

class Point(models.Model):
    name = models.CharField(max_length = 32)
    lon = models.FloatField()
    lat = models.FloatField()

and a view like

def find_points(request):
    from haversine import haversine
    points = []
    all_points = Point.objects.all()
    result_list = []
    your_location = (YOUR_LATITUDE,YOUR_LONGITUDE)
    for point in all_points:
        point_loc = (point.lat,point.lon)
        if(haversine(you,point_loc)<1):
            #print point
            result_list.append(point)
    custom_list = [rec.id for rec in result_list]
    points = Point.objects.filter(id__in=custom_list)
    return render(request,"points.html",{'points':points})

and write points.html like

{% extends "base.html" %}
{% block content %}
<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>
// This example adds a marker to indicate the position
// of Bondi Beach in Sydney, Australia
function initialize() {
    var marker;
    var map;
    var mapOptions = {
        zoom: 16,
        center: new google.maps.LatLng({{latitude}},{{longitude}})
    }
    map = new google.maps.Map(document.getElementById('map-canvas'),
                                mapOptions);

  //var image = '/static/checkmark.png';

  {% for point in points %}
    //console.log({{ point.lat }}, {{ point.lon }});
    var myLatLng = new google.maps.LatLng({{ point.lat }}, {{ point.lon }});

    marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        title: '{{ point.name }}',
        url: '/{{point.id}}',
    });
    google.maps.event.addListener(marker, 'click', function() {
        console.log("here");
        window.location.href = this.url;
    });
  {% endfor %}
}

google.maps.event.addDomListener(window, 'load', initialize);


</script>
<div id="map-canvas"></div>
<div id="map_wrapper">
    <div id="map_canvas" class="mapping"></div>
</div>
<div id="map_wrapper">
    <div id="map-canvas" class="mapping"></div>
</div>
<script type="text/javascript">

var x = document.getElementById("demo");

    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else { 
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }

    function showPosition(position) {
        document.getElementById('latitude').value =  position.coords.latitude ;
        document.getElementById('longitude').value =  position.coords.longitude ;
        x.innerHTML = "Latitude: " + position.coords.latitude + 
        "<br>Longitude: " + position.coords.longitude;  
    }
</script>

{% endblock %}

0👍

I have tried this and kinda fell into trouble since I had some str data type in the data I was feeding the haversine equation.

Here is a snapshot of a working example in looping the haversine equation and getting all values within a specified area(Kilometres).

if form.is_valid():
    lat = form.cleaned_data.get('lat')
    lng = form.cleaned_data.get('lng')
    points = []
    all_points = business_filter.qs
    result_list = []
    selected_location = (lat, lng)

    for point in all_points:
        if isinstance(point.latitude, str) == True:
            break
        elif isinstance(point.longitude, str) == True:
            break

        points = (point.latitude, point.longitude)

        from haversine import haversine, Unit
        result = haversine(selected_location, points)
        if result < 5: ```# check for distance in km```
            result_list.append(point.id)
        
    business_filter = all_points.filter(id__in=result_list).all()        
    filter_count = business_filter.count()

Leave a comment