maposmatic-dev
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Maposmatic-dev] [PATCH 2/2] Js / Nominatim administrative boundaries.


From: Pierre Mauduit
Subject: [Maposmatic-dev] [PATCH 2/2] Js / Nominatim administrative boundaries.
Date: Sun, 20 Dec 2009 23:06:48 +0100

From: Pierre Mauduit <address@hidden>

---
 www/maposmatic/views.py             |   55 ++++++----------------------------
 www/media/icon_alert.png            |  Bin 0 -> 370 bytes
 www/templates/maposmatic/index.html |   21 ++++++++++++-
 3 files changed, 29 insertions(+), 47 deletions(-)
 create mode 100644 www/media/icon_alert.png

diff --git a/www/maposmatic/views.py b/www/maposmatic/views.py
index 5723ed0..d4ce7ab 100644
--- a/www/maposmatic/views.py
+++ b/www/maposmatic/views.py
@@ -26,7 +26,7 @@
 from django.core.paginator import Paginator
 from django.forms.util import ErrorList
 from django.forms import CharField, ChoiceField, FloatField, RadioSelect, \
-                         ModelForm, ValidationError
+                         ModelForm, ValidationError, IntegerField, HiddenInput
 from django.shortcuts import get_object_or_404, render_to_response
 from django.http import HttpResponseRedirect, HttpResponseBadRequest, 
HttpResponse
 from django.utils.translation import ugettext_lazy as _
@@ -49,45 +49,11 @@ except ImportError:
     except ImportError:
         from json import write as json_encode
 
-
-# Test if a given city has its administrative boundaries inside the
-# OpenStreetMap database. We don't go through the Django ORM but
-# directly to the database for simplicity reasons.
-def city_exists(city):
-
-    # If not GIS database is configured, bypass the city_exists check by
-    # returning True.
-    if not www.settings.has_gis_database():
-        return True
-
-    try:
-        conn = psycopg2.connect("dbname='%s' user='%s' host='%s' 
password='%s'" %
-                                (www.settings.GIS_DATABASE_NAME,
-                                 www.settings.DATABASE_USER,
-                                 www.settings.DATABASE_HOST,
-                                 www.settings.DATABASE_PASSWORD))
-    except psycopg2.OperationalError:
-        return False
-
-    try:
-        cursor = conn.cursor()
-        cursor.execute("""select count(*) from planet_osm_line where
-                        boundary='administrative' and
-                        admin_level='8' and
-                        name=%s""",
-                       (city,))
-        result = cursor.fetchall()
-        return (result[0][0] == 1)
-    finally:
-        conn.close()
-
-
 class MapRenderingJobForm(ModelForm):
     class Meta:
         model = MapRenderingJob
         fields = ('maptitle', 'administrative_city', 'lat_upper_left',
-                  'lon_upper_left', 'lat_bottom_right', 'lon_bottom_right',
-                  'administrative_osmid')
+                  'lon_upper_left', 'lat_bottom_right', 'lon_bottom_right')
 
     modes = (('admin', _('Administrative boundary')),
              ('bbox', _('Bounding box')))
@@ -97,6 +63,8 @@ class MapRenderingJobForm(ModelForm):
                                               FloatField(), FloatField()))
     map_language = ChoiceField(choices=www.settings.MAP_LANGUAGES)
 
+    administrative_osmid = IntegerField(widget=HiddenInput)
+
     def clean(self):
         cleaned_data = self.cleaned_data
 
@@ -109,10 +77,6 @@ class MapRenderingJobForm(ModelForm):
                 msg = _(u"Administrative city required")
                 self._errors["administrative_city"] = ErrorList([msg])
                 del cleaned_data["administrative_city"]
-            elif not city_exists(city):
-                msg = _(u"No administrative boundaries found for this city. 
Try with proper casing.")
-                self._errors["administrative_city"] = ErrorList([msg])
-                del cleaned_data["administrative_city"]
 
             # No choice, the map title is always the name of the city
             cleaned_data["maptitle"] = city
@@ -157,11 +121,11 @@ class MapRenderingJobForm(ModelForm):
 
         return cleaned_data
 
-def rendering_already_exists(city):
+def rendering_already_exists(osmid):
     # First try to find rendered items
     rendered_items = (MapRenderingJob.objects.
                       filter(submission_time__gte=datetime.datetime.now() - 
datetime.timedelta(1)).
-                      filter(administrative_city=city).
+                      filter(administrative_osmid=osmid).
                       
filter(status=2).filter(resultmsg="ok").order_by("-submission_time")[:1])
 
     if len(rendered_items):
@@ -172,7 +136,7 @@ def rendering_already_exists(city):
     # Then try to find items being rendered or waiting for rendering
     rendered_items = (MapRenderingJob.objects.
                       filter(submission_time__gte=datetime.datetime.now() - 
datetime.timedelta(1)).
-                      filter(administrative_city=city).
+                      filter(administrative_osmid=osmid).
                       filter(status__in=[0,1]).
                       order_by("-submission_time")[:1])
 
@@ -189,9 +153,10 @@ def index(request):
             job = MapRenderingJob()
             job.maptitle = form.cleaned_data['maptitle']
             job.administrative_city = form.cleaned_data['administrative_city']
+            job.administrative_osmid = 
form.cleaned_data['administrative_osmid']
 
-            if job.administrative_city:
-                url = rendering_already_exists(job.administrative_city)
+            if job.administrative_osmid:
+                url = rendering_already_exists(job.administrative_osmid)
                 if url:
                     request.session['redirected'] = True
                     return HttpResponseRedirect(url)
diff --git a/www/media/icon_alert.png b/www/media/icon_alert.png
new file mode 100644
index 
0000000000000000000000000000000000000000..b00d9850ca91f37cca0ef93447aad38dbb51d145
GIT binary patch
literal 370
address@hidden(olHy`uVBq!ia0vp^0zk~q!3-pCt=%sRq!^2X+?^QKos)S9<Rk?6gt!9f
zzi-<9f4%klj`!<B#lIiK-P>address@hidden&4D_3M_?>yxd29wxtDY5sbi%<sEF
zuMgz?xgYiWUf91c=U(s2e7!w#PmR#)4eo#6FZ}m$)8BV9{(aj2=TX}KZ;$`~|9?1%
zs~lu;NswPKgTu2MX&address@hidden>CcQ
zi0TV`(`c3f3e|bKIEHXs5ABT>YE}?nsdO>a$`Wu5EPGdfTA*X;m-z2~jLDJ>q6=~Z
ztpfjRywGF`DsTMN%G%1Vdu{at*M()address@hidden;v^otopU_aorKR^!e21-x6<ov}G-JJq5i
zZnx*DWS3u$>ZivZPi_=CbnEi(zYpdtKe;K-*?6Du&#UY`wTx!-cuKu1-&_N_gu&C*
K&t;address@hidden

literal 0
HcmV?d00001

diff --git a/www/templates/maposmatic/index.html 
b/www/templates/maposmatic/index.html
index ab09adb..3cfe43a 100644
--- a/www/templates/maposmatic/index.html
+++ b/www/templates/maposmatic/index.html
@@ -70,12 +70,28 @@ function validate_city_search()
   $.getJSON("/nominatim/" + searchPat,
             function(data){
               $("#result_nominatim_search").empty();
+
               $.each(data, function(i,item){
-                $("#result_nominatim_search").append("<li><input 
type=\"radio\" name=\"nom_search_grp\" value=\""+item.place_id+"\" 
/>"+item.display_name+"</li>");
+               if (typeof item.ocitysmap_params == "undefined")
+               {
+                 $("#result_nominatim_search").append("<li><img 
src=\"/smedia/icon_alert.png\" alt=\"Work In Progress\" />&nbsp;<label 
class=\"place_unavailable\""
+                   + ">" +item.display_name + "\"</label></li>");
+                }
+               else
+                {
+                  $("#result_nominatim_search").append("<li><input 
onchange=\"javascript:update_hidden(this,'"
+                    +item.display_name+"');\" type=\"radio\" 
name=\"administrative_tmp_osmid\" value=\""
+                    +item.ocitysmap_params['id']+"\" 
/>"+item.display_name+"</li>");
+                }
               }
             );
            });
 }
+function update_hidden(obj, nloc)
+{
+  document.getElementById("id_administrative_osmid").value = obj.value;
+  document.getElementById("id_administrative_city").value = nloc;
+}
 
 {% endblock %}
 
@@ -159,13 +175,14 @@ maps.{% endblocktrans %}</p>
     <tr class="byadmin field"><td>
         {{ form.administrative_city }}
        <input type="button" onclick="javascript:validate_city_search();" 
value="{% trans "search" %}" />
+       {{ form.administrative_osmid }}
+       {{ form.administrative_osmid.errors }}
         {{ form.administrative_city.errors }}
     </td></tr>
 
     <tr class="bybbox label"><td>{% trans "Title of the map:" %}</td></tr>
     <tr class="bybbox field"><td>
         {{ form.maptitle }}
-       {{ form.administrative_osmid }}
         {{ form.maptitle.errors }}
     </td></tr>
 
-- 
1.6.5.7





reply via email to

[Prev in Thread] Current Thread [Next in Thread]