Google maps api works with manualy inserting json but not with inserting the same json from a python script

huangapple go评论68阅读模式
英文:

Google maps api works with manualy inserting json but not with inserting the same json from a python script

问题

I understand that you have a code snippet that involves passing a JSON with locations to display and route a map using the Google Maps API, and you are facing issues when using the location_json variable. The error message you provided, "Geocode was not successful for the following reason: INVALID_REQUEST," indicates there might be an issue with the format of the location_json variable.

Here is the relevant translated code:

var location_json = {{ location_json|tojson|safe }};

// Rest of your JavaScript code

The problem seems to be with how the location_json variable is formatted when you use it. In the working example, you define the location_json as an array of objects with escaped HTML entities (") for quotes. However, in your problematic code, you seem to be using Python's Jinja template syntax ({{ location_json|tojson|safe }}) to insert the JSON into your JavaScript, which could be causing issues.

To resolve the issue, you should ensure that the format of the location_json variable is the same as in your working example, with escaped quotes, when you use it in your JavaScript code.

If you're having issues with the formatting of location_json within your Python code or template, you may need to adjust the way you're generating this JSON data to match the format you need in your JavaScript code. Make sure the JSON data is correctly formatted with escaped quotes and follows the same structure as in your working example.

英文:

Pretty new to this so thanks in advance. I am trying to pass a location_json with locations in an html file to show and route a map between them using google maps api. when i manually enter the location_json it works fine ,for example like that :

<!DOCTYPE html>
<html>
<head>
    <title>Map with Locations and Route</title>
    <link rel="stylesheet" type="text/css" href="static/main.css">
    <style>
        #map {
            height: 100%;
        }

        #map-container {
            height: 400px;
            width: 100%;
        }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?key=my_api_key"></script>
    <script>
        var location_json = [{"Location":"Apollonia, Sifnos, Greece"},{"Location":"Artemonas, Sifnos, Greece"},{"Location":"Church of Panagia tis Kimisis, Sifnos, Greece"},{"Location":"Church of Panagia Mirtidiotissa, Sifnos, Greece"},{"Location":"Faros Beach, Sifnos, Greece"}];
        
        var locations = location_json;

        function initMap() {
            var geocoder = new google.maps.Geocoder();

            // Get coordinates of all the locations
            var locationCoordinates = [];
            var completedRequests = 0;

            function geocodeLocation(index) {
                if (index < locations.length) {
                    geocoder.geocode({ address: locations[index].Location }, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            locationCoordinates[index] = results[0].geometry.location;
                            completedRequests++;
                        } else {
                            console.log("Geocode was not successful for the following reason: " + status);
                        }

                        if (completedRequests === locations.length) {
                            createMapAndRoute(locationCoordinates);
                        } else {
                            geocodeLocation(index + 1);
                        }
                    });
                }
            }

            geocodeLocation(0);
        }

        function createMapAndRoute(locationCoordinates) {
            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 13,
                center: locationCoordinates[0]
            });

            var directionsService = new google.maps.DirectionsService();
            var directionsRenderer = new google.maps.DirectionsRenderer({ map: map });

            var origin = locationCoordinates[0];
            var destination = locationCoordinates[locationCoordinates.length - 1];

            var waypoints = [];
            for (var i = 1; i < locationCoordinates.length - 1; i++) {
                waypoints.push({ location: locationCoordinates[i] });
            }

            var request = {
                origin: origin,
                destination: destination,
                waypoints: waypoints,
                travelMode: google.maps.TravelMode.DRIVING
            };

            directionsService.route(request, function(result, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsRenderer.setDirections(result);
                } else {
                    console.log("Directions request failed due to " + status);
                }
            });
        }
    </script>
</head>
<body onload="initMap()">
    <div id="map-container">
        <div id="map"></div>
    </div>
</body>
</html>

but if i insert
var location_json = {{ location_json|tojson|safe }};
with the exact same location_json (copy pasted from print command in python terminal)
instead of
var location_json = [{"Location":"Apollonia, Sifnos, Greece"},{"Location":"Artemonas, Sifnos, Greece"},{"Location":"Church of Panagia tis Kimisis, Sifnos, Greece"},{"Location":"Church of Panagia Mirtidiotissa, Sifnos, Greece"},{"Location":"Faros Beach, Sifnos, Greece"}];
it gives a blank page with a console error
Geocode was not successful for the following reason: INVALID_REQUEST

i have tried changing the capitals and inserting commas between address city and country in the pandas file from which i create the json. The objective is to show a map with the locations a route planned between them in the order they appear on the json

答案1

得分: 1

从你的评论中可以看出,你执行了 location_json = locations_df.to_json(orient='records') 并将 location_json(即JSON字符串)传递给模板。然后在模板内部,你再次使用 tojson 过滤器对 location_json 进行序列化。你应该将一个字典列表传递给模板。

查看以下区别:

data = [{"Location":"Apollonia, Sifnos, Greece"},
        {"Location":"Faros Beach, Sifnos, Greece"}]

import json
from jinja2 import Environment, BaseLoader

templ = """var data = {{ data|tojson|safe }}"""
template = Environment(loader=BaseLoader).from_string(templ)

print(template.render(data=data))  # 这是你应该做的 - 将 `data` 作为字典列表传递
print(template.render(data=json.dumps(data))) # 这是你正在做的 - 传递JSON字符串

渲染输出:

var data = [{"Location": "Apollonia, Sifnos, Greece"}, {"Location": "Faros Beach, Sifnos, Greece"}]
var data = "\"[{\"Location\": \"Apollonia, Sifnos, Greece\"}, {\"Location\": \"Faros Beach, Sifnos, Greece\"}]\""

你也可以检查生成的“空白”页面的源HTML。

所以,如果你的数据框 df 看起来像这样:

                     Location
0    Apollonia, Sifnos, Greece
1  Faros Beach, Sifnos, Greece

你可以这样做:

data = list(df.to_dict('index').values())
print(template.render(data=data))

将产生:

var data = [{"Location": "Apollonia, Sifnos, Greece"}, {"Location": "Faros Beach, Sifnos, Greece"}]
英文:

From your comments - you do location_json = locations_df.to_json(orient='records') and pass location_json (i.e. JSON string) to template. Then inside the template you serialize location_json for second time using tojson filter. You should pass a list of dicts to the template.

See the difference:

data = [{"Location":"Apollonia, Sifnos, Greece"},
        {"Location":"Faros Beach, Sifnos, Greece"}]

import json
from jinja2 import Environment, BaseLoader

templ = """var data = {{ data|tojson|safe }}"""
template = Environment(loader=BaseLoader).from_string(templ)

print(template.render(data=data))  # that is what you should do - pass `data` as list of dicts
print(template.render(data=json.dumps(data))) # that is what you do - passing JSON string

Rendered output

var data = [{"Location": "Apollonia, Sifnos, Greece"}, {"Location": "Faros Beach, Sifnos, Greece"}]
var data = "[{\"Location\": \"Apollonia, Sifnos, Greece\"}, {\"Location\": \"Faros Beach, Sifnos, Greece\"}]"

You can also check the source HTML of the generated "blank" page.

So, if your dataframe df looks like

                      Location
0    Apollonia, Sifnos, Greece
1  Faros Beach, Sifnos, Greece

you can do

data = list(df.to_dict('index').values())
print(template.render(data=data))

will produce

var data = [{"Location": "Apollonia, Sifnos, Greece"}, {"Location": "Faros Beach, Sifnos, Greece"}]

huangapple
  • 本文由 发表于 2023年4月4日 17:17:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75927598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定