Several pins on flask google map API

I'm currently developing a flask application and I am trying to retrieve coordinates from a mysql database. The database contains latitude and longitude information, and my goal is to display all the markers on the page with their respective lat/lng values. I am attempting to use JavaScript to add these markers, but for some reason it's not working as expected. Any assistance would be greatly appreciated.

Using Flask SQLAlchemy to retrieve lat/lng data

<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>

Answer №1

When working with jinja templates, keep in mind that they are processed on the server side. If you want to use python variables in javascript, it's best to have both the html and js code in the same .html file. Avoid mixing the two codes together; instead, consider making an ajax call to receive a json response with your points. In Flask, you can achieve this by creating an endpoint like the following:

@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})

In your javascript code, you can then call this endpoint to process the json object using fetch for ajax calls, as demonstrated below:

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'
        });

//define the endpoint
var coodAddresses = 'https://yoursite.com/api/coordinates';
var locations = []; //array to hold coordinates

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() {
                var pos = {
                    lat: lat,
                    lng: lng
                };
                infoWindow.setMap(map);
                infoWindow.setPosition(pos);
                infoWindow.setContent('An error occurred, we are unable to retreive cordinates.');

            });
      }

Remember to ensure that the bounds include all your points if they are not near each other. I hope you find this information helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing the JavaScript Array.find() method to ensure accurate arithmetic calculations within an array of objects

I have a simple commission calculation method that I need help with. I am trying to use the Array.find method to return the calculated result from the percents array. The issue arises when I input a price of 30, as it calculates based on the previous objec ...

Sending data from Web Service to Ajax Request success callback function

Hello Coding Comrades, I am currently working on a form with a SSN textbox that triggers an ajax request to determine if an employee has been hired before. The data returned from the Web Method is in the form of a TermedEmployee Object, but I'm stru ...

How can CakePHP 3 perform a table join using a different table?

I have been working on creating a DB structure that involves the following entities: https://i.sstatic.net/GvVtq.gif My focus is on establishing the relationship between: sales_transaction products products_in_transaction My goal is to set up the rela ...

Performing a $.POST request on a Squarespace webpage

I created a custom form on my website for booking appointments, and it posts to a third-party server. When I submit the form using the <form> tag, I receive the email notification. However, I want to submit the form using $.POST so that I can customi ...

JavaScript script that parses innerHTML

Does the behavior of element.innerHTML = '<script>alert()</script>'; differ across browsers? Can I consistently expect innerHTML to not parse scripts? ...

A function that listens for the onmouseover event and updates the image source of an HTML img element

I have created a function that positions my objects based on the array they are assigned to. For example, if they are in players[0], they will be placed in one position, and if they are in players[1], they will be placed elsewhere. The X and Y values are ...

Error in node - Invalid URI received during npm-request operations

var request = require('request'); var options = { url: 'https://connect1on1.com/api/web/index.php/v1/message/save-message', method:'POST', body:JSON.stringify({"id": data.user_id, "message": data.me ...

Utilizing the jexcel plugin to seamlessly integrate arrays for a personalized subtitle editing experience

Could you please assist me in understanding how to utilize the jexcel plugin for pushing arrays? To achieve the push functionality, I would like it to behave similarly to arrays containing 6 different colors as outlined below: Subtitles = orange, Caption ...

What is the best way to import tab-delimited data from a text file into a MySQL database using CodeIgniter?

I currently have a file with a .dat extension that contains data from my biometric machine. My goal is to upload this file to my server and import its contents into a MySQL database. Here is how the file looks: https://i.sstatic.net/wgvdO.png The structu ...

Having trouble with blockUI compatibility on Internet Explorer 11?

I have encountered an issue with a piece of code that functions correctly in Chrome and FF, but not in ie11. Interestingly enough, when I tested it in ie8, it worked perfectly fine. Has anyone else experienced similar problems with blockUI on ie11? The s ...

"Enhancing Forms with Multiple Event Listeners for Seamless Sub

I'm working on creating a countdown timer with 3 buttons for controlling the timer: start, cancel, and pause. The timer itself is a text input field where you can enter a positive integer. I need to use core JavaScript, not jQuery Start Button: Init ...

Creating Blurry Text Effects in HTML (Step-by-Step Tutorial)

I have a basic text that is centered inside the canvas. However, it appears blurry and unattractive. Can anyone suggest how to enhance its appearance? // Populate the signature canvas with data var canvas = document.getElementById("signatureCanvas"); v ...

Refresh all $(document).ready(); functions after AJAX has finished loading

I find myself in the midst of customizing an application where my access is limited to just one CSS file and one JS file. Unfortunately, I cannot modify the existing markup or scripts, which leaves me with the challenge of adding my own styles and function ...

Modify the background of a div and an image

My goal is to add a background to both the image and the div itself, similar to what I've seen on Amazon. However, I'm struggling to achieve this effect where the white background of the image doesn't show when applied onto the div: Image w ...

Tips for utilizing import alongside require in Javascript/Typescript

In my file named index.ts, I have the following code snippet: const start = () => {...} Now, in another file called app.ts, the code is as follows: const dotenv = require('dotenv'); dotenv.config(); const express = require('express' ...

Whenever a POST request is received, Flask always replies with a status code of 400

During my work on a project using Vue.js with Flask, I encountered a bug related to POST requests. Flask consistently responds with a 400 error code for all requests. To replicate the issue, follow these steps: main.py import os from ...

Tips for invoking a url with JavaScript and retrieving the response back to JavaScript

I am trying to make a URL call from JavaScript with a single parameter, and the URL should respond to that specific request. Here is an example of the response format: {"success":true, "result": {"token":"4fc5ef2bd77a3","serverTime":1338371883,"expireT ...

Ways to identify when a jQuery ajax request has finished executing?

Currently, I have a dropdown menu of countries that is populated using a jQuery ajax call. The issue I am facing is determining when the call is complete so that I can correctly select a country afterwards. Any function I call after the ajax function is tr ...

Testing the unit with a customized header in the interceptor

I've been struggling to execute a unit test within an Angular 6 interceptor, but despite numerous attempts, I keep encountering the following error: Error: Expected one matching request for criteria "Match by function: ", found none. I'm rela ...

What is the process by which a JavaScript Date object is converted to a string when you log it to the

Whenever I create objects in JavaScript and output them to the console, I typically see a JavaScript object displayed. For instance: var myObj = { bla: "foo" } console.log(myObj); This code will display: { bla: "foo" } However, whe ...