简体   繁体   中英

Why I get error when I pass json data from google map API?

def map():
if request.method == 'POST':
    key = "googleMapAPIkey"
    orilist = request.form['from'].split()
    deslist = request.form['to'].split()
    mode = request.form.get('traffic_mode')
    ori = ""
    des = ""
    for word in orilist:
        ori = ori + word + "+"
    ori = ori[:-1]
    for word in deslist:
        des = des + word + "+"
    des=des[:-1]
    url = "https://maps.googleapis.com/maps/api/directions/json?origin="+ori+\
          "&destination="+des+"&key="+key
    print ori,des,mode,url
    r = requests.get(url)
    direction1 = r.json()

    markerArray = []
    print json.dumps(direction1)
    return render_template('googlemap.html', direction1=json.dumps(direction1), ori=request.form['from'], des=request.form['to'], mode=mode,method='POST')
else:
    print request.method
    return render_template('index.html',method='GET')

Here is the template script

var routes = {{ directions1|tojson }};
var start_point = {{ ori }};
var end_point = {{ des }};
var mode = {{ mode }};
function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 42.880230, lng: -78.878738},
        zoom: 8
    });
    var renderer = new google.maps.DirectionsRenderer();

    var request = {
    travelMode: mode,
    origin: start_point,
    destination: end_point
    };
    renderDirections(map,routes,request)
}

I used the google api to get the response and I tried to pass this value into client-side. I 'm sure I get the JSON-formatted string, and when I tried to open the web, it comes that "TypeError: Undefined is not JSON serializable"

You're trying to get the directions from a variable you haven't defined.

There is no directions1 coming from backend. Try direction1 . (Or rename it in render_template() so they match).


Best practice: copy/paste variable names. Even when you make typos, your code will still work.

Also, it's good to pay attention to the error text itself: "Undefined is... means exactly that: whatever you passed instead of a JSON serializable object ...is undefined .

The first you do when you see this error is: go to render_template() , double-click the variable name to select it and copy/paste in js. Even when it "looks" identical.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM