TypeError: unsupported operand type(s) for -: 'unicode' and 'unicode', coords

63,644

Solution 1

Both the longitude and latitude retrieved from the request and the database are strings (unicode strings) and you are trying to operate on them as if they were numbers.

You should first get the int or float representation of such strings to be able to operate on them as numbers (using -, *, etc)

You can do that by creating a int or float object passing the string as a parameter

latitude = int(request.form['Latitude'])

or

latitude = float(request.form['Latitude'])

Solution 2

Unlike in PHP, Python will not auto-convert from string to float. Use:

errors = []
try:
    latitude = float(request.form['Latitude'])
except ValueError:
    # do something about invalid input
    latitude = 0.0
    errors.append(u"Invalid input for Latitude.")

Solution 3

current['longitude'] and longitude are both unicode strings. You need to convert them to floats if you plan to subtract them.

Share:
63,644
user1869558
Author by

user1869558

Updated on January 14, 2020

Comments

  • user1869558
    user1869558 over 4 years

    full code is HERE

    HTML code

    <input type="hidden" id="Latitude" name="Latitude" value={{Longitude}} />
    <input type="hidden" id="Longitude" name="Longitude" value={{Longitude}} />
    
    document.getElementById("Latitude").value  =  position.coords.latitude;
    document.getElementById("Longitude").value =  position.coords.longitude;    
    

    app.py

    Latitude = request.form['Latitude']
    Longitude = request.form['Longitude']
    
    messages = database.returnMessagesinRange(float(Latitude),float(Longitude))
    

    database.py

    def returnMessagesinRange(longitude,latitude):
        allMessages = Messages.find()
        messagesinRange = []
        for current in allMessages:
            if ((current['longitude']-longitude) * (current['longitude']-longitude) + (current['latitude']-latitude)*(current['latitude']-latitude)) <= 1:
                if messagesinRange == None:
                    messagesinRange = [current['text']]
                else:
                    messagesinRange.append(current['text'])
        return messagesinRange
    

    When this is run, i get

    if ((current['longitude']-longitude) * (current['longitude']-longitude) + (current['latitude']-latitude)*(current['latitude']-latitude)) <= 1:
    
    TypeError: unsupported operand type(s) for -: 'unicode' and 'unicode'
    

    Anyone know why this is happening? thanks.