0

Swear I've done this before, can never figure out what to change

Python

@csrf_exempt
def add_trip_to_map(request):
    trip_id = request.POST['trip_id']
    trip = Trip.objects.get(pk = trip_id)
    orig, dest = trip.load.orig, trip.load.dest
    data = {'orig_lat':str(orig.lat),
            'orig_lon':str(orig.lon),
            'dest_lat':str(dest.lat),
            'dest_lon':str(dest.lon)}
    return HttpResponse(json.dumps(data))

JS

    $.post( "{% url 'add_trip_to_map' %}", { trip_id: trip_id }, function( data ) {
console.log(data);
    //console.log(data["dest_lon"]);

    var marker = new mapboxgl.Marker()
.setLngLat([data["dest_lat"], data["dest_lon"]])
.addTo(map);

console.log(data) looks like this:

{"orig_lat": "33.493100", "orig_lon": "117.131700", "dest_lat": "32.454500", "dest_lon": "99.738100"}

BUT I can't access values in js

lng_lat.js:40 Uncaught Error: Invalid LngLat object: (NaN, NaN)

1 Answer 1

1

I assume your first issue is: the returned value of your post is a string. If so you need to convert it:

 data = JSON.parse(data);

The second issue is related to your lon/lat: they must be in the range -90 ... +90

mapboxgl.accessToken = 'pk.eyJ1IjoiZmFyYWRheTIiLCJhIjoiTUVHbDl5OCJ9.buFaqIdaIM3iXr1BOYKpsQ';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v11', // stylesheet location
    center: [-74.5, 40], // starting position [lng, lat]
    zoom: 9 // starting zoom
});

var data = '{"orig_lat": "33.493100", "orig_lon": "117.131700", "dest_lat": "32.454500", "dest_lon": "99.738100"}';

data = JSON.parse(data);

var lon = (Math.abs(parseFloat(data["dest_lon"])) > 90) ? '90' : data["dest_lon"];
var lat = (Math.abs(parseFloat(data["dest_lon"])) > 90) ? '90' : data["dest_lat"];

var marker = new mapboxgl.Marker()
        .setLngLat([data["dest_lat"], data["dest_lon"]])
        .addTo(map);
<script src='https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css' rel='stylesheet' />


<div id='map' style='width: 400px; height: 300px;'></div>

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for answering my question and double thanks for anticipating and answering my next question
@amchugh89 It's a pleasure to help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.