烧瓶谷歌地图api中的多个标记

时间:2018-04-08 13:51:30

标签: javascript mysql google-maps flask

我正在创建一个烧瓶应用并试图从mysql DB获取坐标,数据库有纬度和经度信息,我想用lat / lng显示页面上的所有标记,并倾向于使用js来添加标记,不知道为什么它不起作用。任何帮助表示赞赏。

使用flask sqlalchemy获取lat / lng信息

<script>
    $(document).ready(function () {
        function initMap() {
            var latlng = {lat: -37.8253632, lng: 144.1404107}; // THIS IS CENTER OF THE MAP
            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 10,
                center: latlng
            });

            google.maps.event.addListenerOnce(map, 'tilesloaded', addMarkers);

            function addMarkers() {
                {% for CarD in page_data %}
                  var point = {lat: {{ CarD.lat }}, lng: {{ CarD.lng }} };
                  var marker = new google.maps.Marker({
                    position: point,
                    map: map,
                    title: '!'
                });
                    {% endfor %}

                marker['infowindow'] = new google.maps.InfoWindow({
                    content: '<div id="content" style="text-align: center"></div>'
                }); // info of the point

            }
        }
    });
</script>

1 个答案:

答案 0 :(得分:0)

您的jinja模板在服务器端进行处理,因此只有js在您的模板中时才将python变量放在javascript中(就像在同一个.html文件中有html和js一样)。另外,我会阻止你混合代码。我建议你做一个ajax调用并收到你的积分的json响应。在烧瓶中你可以做这样的事情

@app.route('/api/coordinates) 
def coordinates():
  addresses = session.query(Coordinates)#however you query your db
  all_coods = [] # initialize a list to store your addresses
  for add in addresses:
     address_details = {
     "lat": add.lat, 
     "lng": add.lng, 
     "title": add.title}
     all_coods.append(address_details)
  return jsonify({'cordinates': all_coods})

然后在你的javascript中你可以调用这个端点然后处理json对象(我​​喜欢使用fetch来进行我的ajax调用)

var map;
function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 16,
          center: new google.maps.LatLng(-33.91722, 151.23064),
          mapTypeId: 'roadmap'
        });

//variable to hold your endpoint
var coodAddresses = 'https://yoursite.com/api/coordinates';
//an array to hold your cordinates
var locations = [];
//Using fetch to process the ajax call 
// if you use fetch, besure to include the source below this line in your template
//<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.js"></script>
fetch(coodAddresses)
.then(function(response) {
 return response.text();
 }).then(function(body) {
 var obj = JSON.parse(body);
 var myAdd = {};
 var addresses = obj.cordinates;
 var l = addresses.length;
 for (i = 0; i < l; i++) {
 myAdd = {
      position: {
          lat: parseFloat(obj.cordinates[i].lat),
          lng: parseFloat(obj.cordinates[i].lng)
                },
          title: obj.cordinates[i].title,
           };
 locations.push(myAdd);
}
locations.forEach(function(feature) {
          var marker = new google.maps.Marker({
            position: feature.position,
            title: feature.title,
            map: map
          });
        });

}).catch(function() {
// if the ajax call fails display an error in an info window
                var pos = {
                    lat: lat,
                    lng: lng
                };
                infoWindow.setMap(map);
                infoWindow.setPosition(pos);
                infoWindow.setContent('An error occurred, we are unable to retreive cordinates.');

            });
      }

我希望你觉得这很有用。如果你的点不在彼此附近,你可能需要确保边界包括所有这些点