Example #1
0
def geocode(rawLocation):
    """

    :rtype : Location
    """
    url = "https://maps.googleapis.com/maps/api/geocode/json?address=%s" % rawLocation.replace(" ","+")

    response = urllib2.urlopen(url)
    geocode = json.load(response)
    #debug
    pprint.pprint(geocode)

    location = Location()
    location.status = geocode["status"].encode('utf_8').decode('utf_8')
    if location.status == "OK":
        location.address = geocode["results"][0]["formatted_address"].encode('utf_8').decode('utf_8')
        location.latlng = ndb.GeoPt(geocode["results"][0]["geometry"]["location"]["lat"], geocode["results"][0]["geometry"]["location"]["lng"])
    else:
        location.address = None
        location.latlng = None

    # Debugs
    print "in geocode"
    print (location.status.encode('utf_8') if location.status else None)
    print type(location.status)
    print (location.address.encode('utf_8') if location.address else None)
    print type(location.address)

    return location
Example #2
0
    def post(self):
        messageid = self.request.get("messageid")
        if messageid == "":
            rawCharacter =  cgi.escape(self.request.get("character"), quote = True)
            rawLocation =   cgi.escape(self.request.get("address"), quote = True)
            # Validate character
            (character, charError) = map.validateCharacter(rawCharacter)
            # Validate location
            location = map.validateLocation(rawLocation)
            error, msgError = "", ""

            # Check validation errors and format error message
            if character == None:
                msgChar = rawCharacter
            else:
                msgChar = str(character.name)

            if charError != "":
                error = charError
                msgError = error
            if location.status != "OK":
                error = (error + " " + location.status.encode('utf_8')).decode('utf_8')
                msgError = error
            if (charError == "") and (location.status == "OK"):
                error = ("Move %s to %s. Got it!" % (msgChar, location.address.encode('utf_8'))).decode('utf_8')
                msgError = ""

            print datetime.datetime.utcnow()
            print "error: " + error.encode('utf_8')
            print type(error)
            print "msgError: " + msgError.encode('utf_8')
            print type(msgError)
            # Store in Message store
            if recordMessage("WebForm", None, self.request.remote_addr, msgChar, location, rawCharacter+" "+rawLocation, msgError):
                print "IN APP:"
                top_msgs(True)
                self.writeHTML(error=error, character=character, location=location)
            else:
                error = "App Error: Failed to insert message."
                self.writeHTML(error=error, character=character, location=location)

        else:
            # Validate messageid and get message
            messagekey = ndb.Key(urlsafe=messageid)
            message = Message()
            message = messagekey.get()
            character = Character.query(Character.name == message.character).get()
            location = Location()
            location.address = message.address
            location.latlng = message.latlng

            # If message found
            if not message:
                error = "App Error: Cannot get message."
                self.writeHTML(error=error, character=None, location=None)

            # If message not found
            else:
                # Write
                self.writeHTML(error="", character=character, location=location)
Example #3
0
  def post(self, request_id):
    location = self.request.get('location')
    # Get request
    request = ndb.Key(urlsafe=request_id).get()
    location = location.split('^')

    # Check if location has been previously used
    existing_location = Location.query(Location.name == location[0], Location.address == location[1]).get()
    if existing_location is None:
      # Add new location
      categories = location[3].split(',')
      coordinates = location[4].split(' ')
      new_location = Location()
      new_location.name = location[0]
      new_location.address = location[1]
      new_location.image_url = location[2]
      for c in categories:
        new_location.categories.append(c)
      new_location.longitude = float(coordinates[0])
      new_location.latitude = float(coordinates[1])
      new_location.put()
      
    else:
      new_location = existing_location

    if request != None:
      # Check if already appended
      add = True
      if len(request.bidders) > 0:
        for bid in request.bidders:
          bid = bid.get()
          if bid.name == self.user_model.username:
            print "Already bid"
            add = False
      if add is True:
          print "Haven't bid"
          bidder = Bidder()
          bidder.sender = self.user_model.key
          bidder.location = new_location.key
          bidder.name = self.user_model.username
          bidder.bid_time = datetime.datetime.now() - datetime.timedelta(hours=8)
          bidder.price = request.price
          bidder.put()
          request.bidders.append(bidder.key)
          request.status = "pending"
          request.put()
    else:
      print "Already connected"

    self.redirect('/feed')
Example #4
0
	def add_location(self, latitude, longitude, type, address=None, picture=None, description=None):
		"""
		Adds a new Location object to the database
		
		Returns the newly created Location object
		"""
		new_location = Location()
		new_location.latitude = latitude
		new_location.longitude = longitude
		new_location.address = address
		new_location.type = type
		new_location.picture = picture
		new_location.description = description
		new_location.save()
		
		return new_location
Example #5
0
  def post(self):

    location = Location()

    logging.info(self.request.get('data'))

    data = simplejson.loads(self.request.get('data'))

    logging.info(data)

    if users.get_current_user():
      location.author = users.get_current_user()
      location.title = data['title']
      location.address = data['address']
      location.city =  data['city']
      location.state =  data['region']
      location.location= data['lat'] + "," + data['lng']
      #location.location = "14.584892,121.05747"
      location.put()

      self.response.out.write('OK')
Example #6
0
db_session.add_all(subway_delays)
db_session.commit()

#
# POINTS OF INTEREST (YELP)
#

# we do just the normal points of interest first, not groceries/parks/etc

os.chdir(os.path.join(data_base, 'yelp'))

points_of_interest = []

with open('yelp_all_processed.json', 'r') as f:
    dct = json.load(f)

for i, e in enumerate(dct):
    l = Location()
    l.name = e['name']
    l.rank = i + 1
    l.rating = e['rating']
    l.review_count = e['review_count']
    l.address = e['address'][0]
    l.categories = e['categories']
    l.geom = 'POINT ({:.8f} {:.8f})'.format(e['longitude'], e['latitude'])
    points_of_interest.append(l)

db_session.add_all(points_of_interest)
db_session.commit()
#
# POINTS OF INTEREST (YELP)
#

# we do just the normal points of interest first, not groceries/parks/etc

os.chdir(os.path.join(data_base, 'yelp'))

points_of_interest = []

with open('yelp_all_processed.json', 'r') as f:
	dct = json.load(f)

for i, e in enumerate(dct):
	l = Location()
	l.name = e['name']
	l.rank = i + 1
	l.rating = e['rating']
	l.review_count = e['review_count']
	l.address = e['address'][0]
	l.categories = e['categories']
	l.geom = 'POINT ({:.8f} {:.8f})'.format(e['longitude'], e['latitude'])
	points_of_interest.append(l)

db_session.add_all(points_of_interest)
db_session.commit()