0

I am using Django, GoogleMaps API, and GeoJSON to draw polygons from the spatial database to map. I wanted to add a title so that when you hover over/click on (don't care which) the name or ID of the polygon shows up. I see from here that "title" would do the trick, but that this only works for point features.

Here are the relevant bits of my code (JS in the Django template):

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=___key___"></script>
<div class="center-div" id="map_div" style="height: 700px; width: 850px;"></div>
<script type="text/javascript">

  var map;
  var gjson;

 google.maps.event.addDomListener(window, "load", function () {

  var map = new google.maps.Map  (document.getElementById("map_div"), {
   mapTypeId: google.maps.MapTypeId.HYBRID
  });

  <!-- function to set color based on polygon object attributes -->
  var getStyle = function(pval, slope, id, name) {
    var color = "gray";

    if ((pval < 0.05 ) && (slope < 0) && (slope != -999)){
      color = "red";
    } else if ((pval < 0.05 ) && (slope > 0)){
      color = "purple";
    } else if ((pval >= 0.05 ) && (slope > 0)){
      color = "blue";
    } else if ((pval >= 0.05 ) && (slope < 0) && (slope != -999)){
      color = "yellow";
    }
    return {
      fillColor: color,
      strokeWeight: 1
      // title only applies to point geometries, do something similar with polygon?
      //title: 'Object ' + id + ', ' + name
    }
 }

  var bound = new google.maps.LatLngBounds();
  {% for obj in qs %}

    var gjson = { "type": "Feature",
            "geometry": {{ obj.poly.geojson|safe }}
            }
    bound.extend( new google.maps.LatLng( {{ obj.centerLat }}, {{ obj.centerLon }}) );
    var features = map.data.addGeoJson(gjson);
    var style = getStyle({{obj.pValue}}, {{obj.slope}}, {{obj.id}}, '{{obj.lakeName}}');
    for (var i = 0; i < features.length; i++) {
         map.data.overrideStyle(features[i], style);
    }

{% endfor %}
map.fitBounds(bound)

});
</script>

In this case, I am passing the Django queryset ({{ qs }}) from my view, which includes the polygonal objects. I am iterating through the queryset and: creating the GeoJSON feature, adding it to the map (and extending the bound so it automatically zooms in on the mapped objects) with a style that depends on some attribute values (pValue, slope, etc.). In the comments of the getStyle function, I have where I would add the title for the object, but since this only applies to point features, it does not work.

What is the alternative of the Google Maps 'title' for polygons?

  • As per the Tour there should be only one question asked per question. – PolyGeo Nov 11 '18 at 7:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.