I'm creating a Flask app that pulls data from a postgresql database using psycopg2. For the user in each row, the database has latitude and longitude info. I want to dynamically plot the users who are active onto my map using markers with this lat/lng information.
Right now, I can get return active user's coordinates using the following in app.py:
def getUserLocation(conn, cur):
cur.execute("""SELECT latitude, longitude FROM user_list WHERE timestamps >
(current_timestamp - make_interval(mins := %s))""", [setTime])
for latitude, longitude in cur.fetchall():
return latitude, longitude
Then this return value is saved as locations .
myConnection = psycopg2.connect(host=hostname, user=username,
password=password, dbname=database)
cur = myConnection.cursor()
locations = getUserLocation (myConnection, cur)
Then it's rendered to Jinja like this:
@app.route("/")
def mapview():
return render_template('index.html', locations=locations)
This is what my add markers function looks like right now, where I try to call these values, and it doesn't work.
function addMarkers() {
{% for location in locations %}
var point = {lat: {{ location.lat }}, lng: {{ location.lng }}};
var marker = new google.maps.Marker({
position: point,
map: map,
});
{% endfor %}
}
How can I render these points on the map dynamically?
Just pass latitude and longitude, and process the points on the client side like this:
<div id="map" style="width: 100%; height: 400px"></div>
<script>
$(document).ready(function(){
function initMap() {
var latlng = { lat: 37.09024, lng: -95.712891 }; // THIS IS CENTER OF THE MAP
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: latlng,
scrollwheel: false,
disableDoubleClickZoom: true,
});
google.maps.event.addListenerOnce(map, 'tilesloaded', addMarkers);
function addMarkers() {
var point = { lat: {{ locations.latitude }}, lng: {{ locations.longitude }} };
var marker = new google.maps.Marker({
position: point,
map: map,
title: '!',
url: '',
});
marker['infowindow'] = new google.maps.InfoWindow({
content: '<div id="content" style="text-align: center">{{ point.info }}</div>'
}); // info of the point
google.maps.event.addListener(marker, 'click', function() {
//window.location.href = this.url;
this['infowindow'].open(map, this);
});
google.maps.event.addListener(marker, 'mouseover', function() {
//this['infowindow'].open(map, this);
});
google.maps.event.addListener(marker, 'mouseout', function() {
//this['infowindow'].close(map, this);
});
}
}
});
</script>
<script src="https://maps.googleapis.com/maps/api/js?v=3&key=YOUR_CODE&callback=initMap" async defer></script>
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.