itsahsiao / breadcrumbs

A full-stack Flask web app that lets foodies search restaurants, track their eating history, while also connecting with friends
28 stars 10 forks source link

Map for current user is displayed across all user profile pages #23

Closed itsahsiao closed 8 years ago

itsahsiao commented 8 years ago

When viewing profile pages of other users, I noticed that the map for Issue #6 is the same across all user profile pages - Sunnyvale is the only city, yes, but the markers are the exact same across all maps.

Need to fix /user-visits.json, as it is passing the current user's user id into the query:

@app.route("/user-visits.json")
def user_restaurant_visits():
    """Return info about user's restaurant visits as JSON."""

    # Query to get all visits for current logged in user (pass in user id from session)
    user_visits = db.session.query(Visit).filter(Visit.user_id == session["current_user"]["user_id"]).all()

    rest_visits = {}

    for visit in user_visits:
        rest_visits[visit.visit_id] = {
            "restaurant": visit.restaurant.name,
            "address": visit.restaurant.address,
            "phone": visit.restaurant.phone,
            "image_url": visit.restaurant.image_url,
            # Need to convert latitude and longitude to floats
            # Otherwise get a TypeError: Decimal is not JSON serializable
            "latitude": float(visit.restaurant.latitude),
            "longitude": float(visit.restaurant.longitude)
        }

    return jsonify(rest_visits)
itsahsiao commented 8 years ago

I used meaningful URL in the backend /users/<int:user_id>/visits.json so that I could pass the user id into the query from the url, and return all restaurant visits for a user.

Now for the Google Map JS, I need to try and pass this meaningful URL into the AJAX get request.

I tried to use Jinja: $.get('/users/{{ user.user_id }}/visits.json', function (visits) {, but I ended up with a 404 error in the browser console when loading the page, as JS is reading the url as exact: GET http://localhost:5000/users/%7B%7B%20user.user_id%20%7D%7D/visits.json 404 (NOT FOUND)

The map loads but no markers! Need to fix the AJAX get request url

itsahsiao commented 8 years ago

To resolve this, I used a html data attribute to store the user id from the user profile page: <div id="user-info" data-userid="{{ user.user_id }}">

Then I defined a global variable at the top of the JS file, which grabs the value from the DOM: var user_id = $("#user-info").data("userid")

I then defined another variable to concatenate a string for the url that needs to be passed into the AJAX get request: var user_visits_json = "/users/" + user_id + "/visits.json";

$.get(user_visits_json, function (visits) { ...