summaryrefslogtreecommitdiff
path: root/app/locations/models.py
blob: f9a3e5b735690c2c9c70ccda5b2d16b7e7de6369 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import json
import requests
from django.urls import reverse
from django.apps import apps
from django.contrib.gis.geos import GEOSGeometry, fromstr, MultiPolygon
from django.contrib.gis.db import models
from django.contrib.sitemaps import Sitemap
from django.utils.safestring import mark_safe
from django.utils import timezone


"http://staticmap.openstreetmap.de/staticmap.php?center=object.location.geometry.centroid.y,object.location.geometry.centroid.x&zoom=14&size=1140x300&maptype=osmarenderer&markers=40.702147,-74.015794,lightblue1"


class Region(models.Model):
    """Model to define arbitrary regions based on where I've been"""
    name = models.CharField(max_length=50)
    slug = models.SlugField()
    pub_date = models.DateTimeField('Date published', null=True)
    geometry = models.MultiPolygonField(srid=4326, null=True)
    lon = models.FloatField('Longitude', help_text="Longitude of centerpoint", null=True)
    lat = models.FloatField('Latitude', help_text="Latitude of centerpoint", null=True)
    zoom_level = models.CharField(max_length=2, null=True)

    def get_absolute_url(self):
        return "/locations/region/%s/" % (self.slug)

    def __str__(self):
        return self.name


class Country(models.Model):
    """
    A geographic model based on the v3 of the simplified world borders multipolygon shapefile from http://thematicmapping.org/downloads/world_borders.php.
    """
    name = models.CharField(max_length=50)
    area = models.IntegerField(help_text="Area of Country in SQ meters")
    pop2005 = models.IntegerField('Population 2005')
    fips = models.CharField('FIPS Code', max_length=2, help_text=mark_safe('<a href="http://www.census.gov/geo/www/fips/fips.html">Federal Information Processing Standard Code</a>'))
    iso2 = models.CharField('2 Digit ISO', max_length=2, help_text=mark_safe('<a href="http://www.iso.org/">International Organization for Standardization</a>'))
    iso3 = models.CharField('3 Digit ISO', max_length=3, help_text=mark_safe('<a href="http://www.iso.org/">International Organization for Standardization</a>'))
    un = models.IntegerField('United Nations Code')
    REGION_CODES = (
        (0, 'MISC'),
        (2, 'Africa'),
        (9, 'Oceania'),
        (19, 'Americas'),
        (142, 'Asia'),
        (150, 'Europe'),
    )
    SUBREGION_CODES = (
        (0, 'MISC'),
        (5, 'South America'),
        (11, 'Western Africa'),
        (13, 'Central America'),
        (14, 'Eastern Africa'),
        (15, 'Northern Africa'),
        (17, 'Middle Africa'),
        (18, 'Southern Africa'),
        (21, 'North America'),
        (29, 'Caribbean'),
        (30, 'Eastern Asia'),
        (34, 'Southern Asia'),
        (35, 'Southeast Asia'),
        (39, 'Southern Europe'),
        (53, 'Australia and New Zealand'),
        (54, 'Melanesia'),
        (57, 'Micronesia'),
        (61, 'Polynesia'),
        (143, 'Central Asia'),
        (145, 'Western Asia'),
        (151, 'Eastern Europe'),
        (154, 'Northern Europe'),
        (155, 'Western Europe'),
    )
    region = models.IntegerField('Region Code', choices=REGION_CODES)
    subregion = models.IntegerField('Sub-Region Code', choices=SUBREGION_CODES)
    lon = models.FloatField('Longitude', help_text="Longitude of centerpoint")
    lat = models.FloatField('Latitude', help_text="Latitude of centerpoint")
    zoom_level = models.CharField(max_length=2, null=True)
    slug = models.SlugField(null=True)
    visited = models.BooleanField(default=False)
    lux_region = models.ForeignKey(Region, on_delete=models.CASCADE, null=True)
    pub_date = models.DateTimeField('Date published', null=True)
    geometry = models.MultiPolygonField('Country Border', srid=4326)

    class Meta:
        ordering = ['name']
        verbose_name_plural = 'Countries'

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return "/locations/%s/" % (self.slug)


class State(models.Model):
    """Model to hold state boundaries"""
    name = models.CharField(max_length=250, blank=True, null=True,)
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    slug = models.SlugField()
    code = models.CharField(max_length=2, null=True, blank=True)
    pub_date = models.DateTimeField('Date published', null=True)
    geometry = models.MultiPolygonField(srid=4326, null=True)

    class Meta:
        ordering = ['name']

    def __str__(self):
        return "%s" % (self.name)

    def get_absolute_url(self):
        return "/locations/%s/%s/" % (self.country.slug, self.slug)


class Location(models.Model):
    """Model to hold location shapes as arbitrarily defined by me"""
    state = models.ForeignKey(State, on_delete=models.CASCADE)
    name = models.CharField(max_length=50, )
    slug = models.SlugField()
    pub_date = models.DateTimeField('Date published')
    geometry = models.MultiPolygonField(srid=4326)

    class Meta:
        ordering = ('-pub_date',)
        get_latest_by = 'pub_date'

    def __str__(self):
        return self.name

    def comma_name(self):
        if self.state.country.name == "United States":
            return self.state
        else:
            return self.state.country

    @property
    def get_previous_admin_url(self):
        return reverse('admin:%s_%s_change' %(self._meta.app_label,  self._meta.model_name),  args=[self.get_previous_by_pub_date().id] )

    @property
    def get_next_admin_url(self):
        model = apps.get_model(app_label=self._meta.app_label, model_name=self._meta.model_name)
        try:
            return reverse('admin:%s_%s_change' %(self._meta.app_label,  self._meta.model_name),  args=[self.get_next_by_pub_date().pk] )
        except model.DoesNotExist:
            return ''

    def get_absolute_url(self):
        return "/locations/%s/%s/%s/" % (self.state.country.slug, self.state.slug, self.slug)


class Route(models.Model):
    """Model to hold routes for longer trips"""
    name = models.CharField(max_length=200)
    slug = models.SlugField()
    zoom = models.CharField(max_length=2, null=True)
    template_var_name = models.CharField(max_length=10, null=True)
    pub_date = models.DateTimeField('Date published', null=True)
    geometry = models.MultiPointField(srid=4326)

    def get_absolute_url(self):
        return "/locations/%s/%s/%s/" % (self.slug)

    def __str__(self):
        return self.name


class CheckIn(models.Model):
    point = models.PointField(blank=True)
    location = models.ForeignKey(Location, on_delete=models.CASCADE, blank=True, null=True)
    date = models.DateField(default=timezone.now)

    class Meta:
        ordering = ('-date',)
        get_latest_by = 'date'

    def __str__(self):
        return str(self.date)

    @property
    def lon(self):
        '''Get the site's longitude.'''
        return self.point.x

    @property
    def lat(self):
        '''Get the site's latitude.'''
        return self.point.y

    def save(self):
        try:
            self.location = Location.objects.filter(geometry__contains=self.point).get()
        except Location.DoesNotExist:
            raise forms.ValidationError("There is no location associated with that point, add it:  %sadmin/locations/location/add/" % (settings.BASE_URL))
        super(CheckIn, self).save()


class WritingbyCountrySitemap(Sitemap):
    changefreq = "weekly"
    priority = 0.6
    protocol = "https"

    def location(self, item):
        return '/jrnl/%s' % item.slug

    def items(self):
        return Country.objects.filter(visited=True)


def get_bounds(lat, lon):
    '''
    given a set of lat,lon coords return the nearest administrative level boundary (usually turn out to be city, but sometimes it's a county, occasionally a state)
    '''
    r = requests.get('http://nominatim.openstreetmap.org/reverse',
                     params={
                         'lat': lat,
                         'lon': lon,
                         'accept-language': 'en',
                         'format': 'json'
                     })
    r.raise_for_status()
    data = json.loads(r.text)
    adr = data.get('address', {})
    city = adr.get('hamlet') or adr.get('village') or adr.get('town') or adr.get('city')
    state = adr.get('state')
    country = adr.get('country')
    r = requests.get('http://nominatim.openstreetmap.org/search',
                     params={
                         'city': city,
                         'state': state,
                         'country': country,
                         'polygon_text': 1,
                         'format': 'json',
                         'featuretype': 'neighborhood'
                     })
    r.raise_for_status()
    data = json.loads(r.text)
    poly = GEOSGeometry(data[0]['geotext'])
    # Sometimes you get a multipolygon, sometimes just a polygon
    if poly.geom_type == 'Polygon':
        poly = MultiPolygon(fromstr(data[0]['geotext']))
    return poly