Skip to content
Browse files

Initial commit, everything works, but it ain't pretty

  • Loading branch information...
0 parents commit c2c969d58e015a08241a1601209639f282f537f1 Mark Ransom committed
19 .gitignore
@@ -0,0 +1,19 @@
+*.pyc
+*.vim
+*.swp
+*.py~
+*.html~
+*.txt~
+.DS_Store
+pip-log.txt
+build
+dist
+*.egg-info
+*.db
+*.tar.gz
+demo/themes/*
+demo/media/themes_archives/
+demo/cms_themes
+demo/database.sqlite
+demo/media
+demo/static
1 AUTHORS
@@ -0,0 +1 @@
+* Mark Ransom <megamark16@gmail.com>
10 LICENSE
@@ -0,0 +1,10 @@
+Copyright (c) 2011, Mark Ransom
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+* Neither the name of the Salva O'Renick nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3 MANIFEST.in
@@ -0,0 +1,3 @@
+include AUTHORS
+include LICENSE
+include README.rst
45 README.rst
@@ -0,0 +1,45 @@
+django-cms-storelocator
+=================
+An extension for Django CMS that lets you enter your store locations and
+drop a plugin on any page that generates a map and store list based on
+city/state or zip code search input, or a city drop down for each city
+with a location in it.
+
+Dependancies
+============
+
+- django (tested with 1.3)
+- django-cms (tested with 2.2)
+
+Getting Started
+=============
+
+To get started simply install using ``pip``:
+::
+ pip install django-cms-storelocator
+
+Add ``store_locator`` to your installed apps and ``syncdb`` (or migrate, if
+you have south installed).
+
+Your installed apps should look something like this:
+::
+ INSTALLED_APPS = (
+ 'django.contrib.auth',
+ 'django.contrib.contenttypes',
+ 'django.contrib.sessions',
+ 'django.contrib.sites',
+ 'django.contrib.messages',
+ 'django.contrib.admin',
+ 'cms',
+ 'store_locator',
+ )
+
+Usage
+=============
+
+You can add store locations through the admin, the app will try to find a
+lat/long via google maps api if you do not enter them.
+
+Once you have your locations entered you can simply drop a Store Locator
+plugin on any page in your Django CMS implementation and magic will happen.
+
38 setup.py
@@ -0,0 +1,38 @@
+from setuptools import setup, find_packages
+import os
+
+version = __import__('cms_themes').__version__
+
+install_requires = [
+ 'setuptools',
+ 'django',
+ 'django-cms',
+]
+
+setup(
+ name = "django-cms-themes",
+ version = version,
+ url = 'http://github.com/megamark16/django-cms-themes',
+ license = 'BSD',
+ platforms=['OS Independent'],
+ description = "Load prepackaged themes (templates and accompanying media) into Django CMS projects through the admin",
+ author = "Mark Ransom",
+ author_email = 'megamark16@gmail.com',
+ packages=find_packages(),
+ install_requires = install_requires,
+ include_package_data=True,
+ zip_safe=False,
+ classifiers = [
+ 'Development Status :: 4 - Beta',
+ 'Framework :: Django',
+ 'Intended Audience :: Developers',
+ 'License :: OSI Approved :: BSD License',
+ 'Operating System :: OS Independent',
+ 'Programming Language :: Python',
+ 'Topic :: Internet :: WWW/HTTP',
+ 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
+ ],
+ package_dir={
+ 'cms_themes': 'cms_themes',
+ },
+)
3 store_locator/__init__.py
@@ -0,0 +1,3 @@
+VERSION = (1,0,0)
+__version__ = "1.0.0"
+
11 store_locator/admin.py
@@ -0,0 +1,11 @@
+from django.contrib import admin, messages
+from models import Location
+from django.conf import settings
+
+class LocationAdmin(admin.ModelAdmin):
+ list_display = ('id','name','address','phone', 'url')
+ list_display_links = ('id','name',)
+ list_filter = ('name',)
+
+admin.site.register(Location, LocationAdmin)
+
26 store_locator/cms_plugins.py
@@ -0,0 +1,26 @@
+from cms.plugin_pool import plugin_pool
+from cms.plugin_base import CMSPluginBase
+from django.utils.translation import ugettext_lazy as _
+from django.conf import settings
+from django.core.urlresolvers import reverse
+from store_locator.models import StoreLocator
+
+class StoreLocatorPlugin(CMSPluginBase):
+ """Subclass of Text plugin, includes 'topic' & 'css' fields"""
+
+ model = StoreLocator
+ name = _("Store Locator Map")
+ render_template = "store_locator/store_locator_map.html"
+
+ def render(self, context, instance, placeholder):
+ get_lat_long_url = reverse('store_locator.views.get_lat_long')
+ get_locations_url = reverse('store_locator.views.get_locations')
+
+ context.update({
+ 'get_lat_long_url': get_lat_long_url,
+ 'get_locations_url': get_locations_url,
+ 'instance': instance,
+ })
+ return context
+
+plugin_pool.register_plugin(StoreLocatorPlugin)
45 store_locator/migrations/0001_initial.py
@@ -0,0 +1,45 @@
+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+class Migration(SchemaMigration):
+
+ def forwards(self, orm):
+
+ # Adding model 'Location'
+ db.create_table('store_locator_location', (
+ ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+ ('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
+ ('address', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
+ ('latitude', self.gf('django.db.models.fields.FloatField')(null=True, blank=True)),
+ ('longitude', self.gf('django.db.models.fields.FloatField')(null=True, blank=True)),
+ ('description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
+ ('phone', self.gf('django.db.models.fields.CharField')(max_length=255)),
+ ('url', self.gf('django.db.models.fields.URLField')(max_length=255, null=True, blank=True)),
+ ))
+ db.send_create_signal('store_locator', ['Location'])
+
+
+ def backwards(self, orm):
+
+ # Deleting model 'Location'
+ db.delete_table('store_locator_location')
+
+
+ models = {
+ 'store_locator.location': {
+ 'Meta': {'object_name': 'Location'},
+ 'address': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+ 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'latitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
+ 'longitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+ 'phone': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+ 'url': ('django.db.models.fields.URLField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'})
+ }
+ }
+
+ complete_apps = ['store_locator']
41 store_locator/migrations/0002_auto__chg_field_location_phone__chg_field_location_address.py
@@ -0,0 +1,41 @@
+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+class Migration(SchemaMigration):
+
+ def forwards(self, orm):
+
+ # Changing field 'Location.phone'
+ db.alter_column('store_locator_location', 'phone', self.gf('django.db.models.fields.CharField')(max_length=255, null=True))
+
+ # Changing field 'Location.address'
+ db.alter_column('store_locator_location', 'address', self.gf('django.db.models.fields.TextField')(max_length=255))
+
+
+ def backwards(self, orm):
+
+ # Changing field 'Location.phone'
+ db.alter_column('store_locator_location', 'phone', self.gf('django.db.models.fields.CharField')(default='', max_length=255))
+
+ # Changing field 'Location.address'
+ db.alter_column('store_locator_location', 'address', self.gf('django.db.models.fields.CharField')(max_length=255))
+
+
+ models = {
+ 'store_locator.location': {
+ 'Meta': {'object_name': 'Location'},
+ 'address': ('django.db.models.fields.TextField', [], {'max_length': '255', 'blank': 'True'}),
+ 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'latitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
+ 'longitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+ 'phone': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+ 'url': ('django.db.models.fields.URLField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'})
+ }
+ }
+
+ complete_apps = ['store_locator']
64 store_locator/migrations/0003_auto__add_storelocator.py
@@ -0,0 +1,64 @@
+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+class Migration(SchemaMigration):
+
+ def forwards(self, orm):
+
+ # Adding model 'StoreLocator'
+ db.create_table('cmsplugin_storelocator', (
+ ('cmsplugin_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['cms.CMSPlugin'], unique=True, primary_key=True)),
+ ('distance', self.gf('django.db.models.fields.IntegerField')(default=25)),
+ ))
+ db.send_create_signal('store_locator', ['StoreLocator'])
+
+
+ def backwards(self, orm):
+
+ # Deleting model 'StoreLocator'
+ db.delete_table('cmsplugin_storelocator')
+
+
+ models = {
+ 'cms.cmsplugin': {
+ 'Meta': {'object_name': 'CMSPlugin'},
+ 'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
+ 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+ 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+ 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}),
+ 'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}),
+ 'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
+ 'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
+ 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
+ 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
+ },
+ 'cms.placeholder': {
+ 'Meta': {'object_name': 'Placeholder'},
+ 'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'slot': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'})
+ },
+ 'store_locator.location': {
+ 'Meta': {'object_name': 'Location'},
+ 'address': ('django.db.models.fields.TextField', [], {'max_length': '255', 'blank': 'True'}),
+ 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'latitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
+ 'longitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+ 'phone': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+ 'url': ('django.db.models.fields.URLField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'})
+ },
+ 'store_locator.storelocator': {
+ 'Meta': {'object_name': 'StoreLocator', 'db_table': "'cmsplugin_storelocator'", '_ormbases': ['cms.CMSPlugin']},
+ 'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}),
+ 'distance': ('django.db.models.fields.IntegerField', [], {'default': '25'})
+ }
+ }
+
+ complete_apps = ['store_locator']
0 store_locator/migrations/__init__.py
No changes.
75 store_locator/models.py
@@ -0,0 +1,75 @@
+import tarfile
+import StringIO
+import shutil
+import os
+import math
+from django.conf import settings
+from django.db import models
+from cms.models import CMSPlugin
+
+class LocationManager(models.Manager):
+ def __init__(self):
+ super(LocationManager, self).__init__()
+
+ def near(self, source_latitude, source_longitude, distance):
+ queryset = super(LocationManager, self).get_query_set()
+ rough_distance = distance / 2
+ queryset = queryset.filter(
+ latitude__range=(source_latitude - rough_distance, source_latitude + rough_distance),
+ longitude__range=(source_longitude - rough_distance, source_longitude + rough_distance)
+ )
+ locations = []
+ for location in queryset:
+ if location.latitude and location.longitude:
+ exact_distance = self.GetDistance(
+ source_latitude, source_longitude,
+ location,
+ )
+ if exact_distance <= distance:
+ setattr(location, 'distance', exact_distance)
+ locations.append(location)
+ #print "%s - %s" % (location, exact_distance)
+
+ return locations
+ #queryset = queryset.filter(id__in=[l.id for l in locations])
+ #return queryset
+
+ def GetDistance(self, source_latitude, source_longitude, target_location):
+ lat_1 = math.radians(source_latitude)
+ long_1 = math.radians(source_longitude)
+
+ lat_2 = math.radians(target_location.latitude)
+ long_2 = math.radians(target_location.longitude)
+
+ dlong = long_2 - long_1
+ dlat = lat_2 - lat_1
+ a = (math.sin(dlat / 2))**2 + math.cos(lat_1) * math.cos(lat_2) * (math.sin(dlong / 2))**2
+ c = 2 * math.asin(min(1, math.sqrt(a)))
+ dist = 3956 * c
+ return dist
+
+
+class Location(models.Model):
+ name = models.CharField(max_length=255)
+ address = models.TextField(max_length=255, blank=True)
+ latitude = models.FloatField(blank=True, null=True)
+ longitude = models.FloatField(blank=True, null=True)
+ description = models.TextField(blank=True, null=True)
+ phone = models.CharField(max_length=255, blank=True, null=True)
+ url = models.URLField(max_length=255, blank=True, null=True)
+
+ objects = LocationManager()
+
+ class Meta:
+ verbose_name = "Store Location"
+ verbose_name_plural = "Store Locations"
+
+ def __unicode__(self):
+ return self.name
+
+ def get_single_line_address(self):
+ return self.address.replace('\n', ', ')
+
+class StoreLocator(CMSPlugin):
+ distance = models.IntegerField(default=25)
+
99 store_locator/templates/store_locator/store_locator_map.html
@@ -0,0 +1,99 @@
+<h1>Store Locator</h1>
+
+<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
+<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
+
+<form>
+ <input type="text" id="locations_search_field" />
+ <select id="distance_field">
+ <option value="1">1 Mile</option>
+ <option value="5">5 Miles</option>
+ <option value="10">10 Miles</option>
+ <option value="15">15 Miles</option>
+ <option value="25" selected="selected">25 Miles</option>
+ <option value="50">50 Miles</option>
+ <option value="100">100 Miles</option>
+ </select>
+ <input type="submit" onClick="location_search(); return false;" value="Search" />
+</form>
+<br />
+<div id="map_canvas" style="width:600px; height:400px"></div>
+
+<script type="text/javascript">
+ var zoom_list = {
+ "1" : 13,
+ "5" : 12,
+ "10" : 11,
+ "15" : 11,
+ "25" : 10,
+ "50" : 9,
+ "100" : 8,
+ }
+ var markers = new Array;
+ var latlng = new google.maps.LatLng(39.0997265,-94.5785667);
+ var myOptions = {
+ zoom: 10,
+ center: latlng,
+ mapTypeId: google.maps.MapTypeId.ROADMAP
+ };
+ var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
+ var infoWindow = new google.maps.InfoWindow();
+ var search_value = '';
+ document.map = map;
+ function clear_markers() {
+ for (i in markers) {
+ markers[i].setMap(null);
+ }
+ markers.length = 0;
+ }
+
+ function location_search() {
+ clear_markers();
+ var get_lat_long_url = "{{ get_lat_long_url }}";
+ var get_locations_url = "{{ get_locations_url }}";
+ search_value = $("#locations_search_field").val();
+ var distance = $("#distance_field").val();
+ var new_zoom = zoom_list[distance];
+ $.get(get_lat_long_url + "?q=" + search_value, function(data) {
+ var latitude = data.split(',')[2];
+ var longitude = data.split(',')[3];
+ map.setZoom(new_zoom);
+ var marker = new google.maps.Marker({
+ position: new google.maps.LatLng(latitude, longitude),
+ title: search_value
+ });
+ google.map
+ marker.setMap(map);
+ markers.push(marker);
+ map.setCenter(marker.position);
+ $.getJSON(get_locations_url + "?lat=" + latitude + "&long=" + longitude + "&distance=" + distance, function(data) {
+ $.each(data, function() {
+ location_info = this;
+ var location_marker = new google.maps.Marker({
+ position: new google.maps.LatLng(location_info.latitude, location_info.longitude),
+ title: location_info.name
+ });
+ location_marker.setMap(map);
+ markers.push(location_marker);
+ google.maps.event.addListener(location_marker, "click", get_location_marker_click_listener(location_info, location_marker));
+ });
+ });
+ });
+ }
+
+ function get_location_marker_click_listener(location_info, location_marker) {
+ return function() {
+ content = "<strong>" + location_info.name + "</strong><br>" +
+ location_info.address.replace(/\n/g, '<br />') + "<br>" +
+ "<a href='http://maps.google.com/maps?saddr=" + search_value + "&daddr=" + location_info.address + "'>Directions</a>";
+ if (location_info.phone != '') {
+ content += "<br><strong>Phone:</strong> " + location_info.phone;
+ }
+
+ infoWindow.setContent(content);
+ infoWindow.open(map, location_marker);
+
+ }
+ }
+</script>
+
7 store_locator/urls.py
@@ -0,0 +1,7 @@
+from django.conf.urls.defaults import *
+from store_locator import views
+
+urlpatterns = patterns('',
+ (r'^get_lat_long/$', views.get_lat_long),
+ (r'^get_locations/$', views.get_locations),
+)
39 store_locator/views.py
@@ -0,0 +1,39 @@
+import urllib2
+import urllib
+import json
+
+from django.core.urlresolvers import reverse
+from django.http import HttpResponse, Http404, HttpResponseRedirect
+from django.shortcuts import render_to_response, get_object_or_404
+from django.template import RequestContext
+from store_locator.models import Location
+
+def get_lat_long(request):
+ if not request.GET.get('q'):
+ return ''
+ args = urllib.urlencode({'q': request.GET.get('q')})
+ r = urllib2.urlopen("http://maps.google.com/maps/geo?output=csv&%s" % args)
+ return HttpResponse(r.read())
+
+def get_locations(request):
+ try:
+ latitude = float(request.GET.get('lat'))
+ longitude = float(request.GET.get('long'))
+ distance = int(request.GET.get('distance', 25))
+ except:
+ return HttpResponse('[]')
+
+ locations = Location.objects.near(latitude, longitude, distance)
+ json_locations = []
+ for location in locations:
+ location_dict = {}
+ location_dict['name'] = location.name
+ location_dict['address'] = location.address
+ location_dict['latitude'] = location.latitude
+ location_dict['longitude'] = location.longitude
+ location_dict['distance'] = location.distance
+ location_dict['description'] = location.description
+ location_dict['url'] = location.url
+ location_dict['phone'] = location.phone
+ json_locations.append(location_dict)
+ return HttpResponse(json.dumps(json_locations), mimetype="application/json")

0 comments on commit c2c969d

Please sign in to comment.
Something went wrong with that request. Please try again.