Coder Social home page Coder Social logo

flask-extensions / flask-googlemaps Goto Github PK

View Code? Open in Web Editor NEW
635.0 33.0 194.0 6.26 MB

Easy way to add GoogleMaps to Flask applications. maintainer: @getcake

Home Page: https://flask-googlemaps.com

License: MIT License

HTML 21.85% Python 77.12% Makefile 1.03%
flask flask-extensions map maps googlemaps google-maps google-maps-api hacktoberfest hacktoberfest2020

flask-googlemaps's Introduction

Flask Google Maps Generic badge

Flask Estension PyPI version fury.io PyPI download month PyPI license PyPI format PyPI status CI-Github Code style: black

Easy to use Google Maps in your Flask application

requires

Contribute

To contribute with the project, clone it, create a virtualenv and install all of you need to dev, see below:

git clone https://github.com/flask-extensions/Flask-GoogleMaps.git
cd Flask-GoogleMaps
poetry use env 3.8  # just to create virtualenv at the first time
poetry shell # activate virtualenv
poetry install  # to install all for dev
pre-commit install # to install pre-commit hooks

Installation

To use in your project just use your dependency manager to install it, with pip is like this:

pip install flask-googlemaps

How it works

Flask-GoogleMaps includes some global functions and template filters in your Jinja environment, also it allows you to use the Map in views if needed.

registering

in your app

from flask import Flask
from flask_googlemaps import GoogleMaps

app = Flask(__name__)

# you can set key as config
app.config['GOOGLEMAPS_KEY'] = "8JZ7i18MjFuM35dJHq70n3Hx4"

# Initialize the extension
GoogleMaps(app)

# you can also pass the key here if you prefer
GoogleMaps(app, key="8JZ7i18MjFuM35dJHq70n3Hx4")

In template

{{googlemap("my_awesome_map", lat=0.23234234, lng=-0.234234234, markers=[(0.12,
-0.45345), ...])}}

That's it! now you have some template filters and functions to use, more details in examples and screenshot below.

Usage

  • You can create the map in the view and then send to the template context
  • you can use the template functions and filters directly

1. View

from flask import Flask, render_template
from flask_googlemaps import GoogleMaps
from flask_googlemaps import Map

app = Flask(__name__, template_folder=".")
GoogleMaps(app)

@app.route("/")
def mapview():
    # creating a map in the view
    mymap = Map(
        identifier="view-side",
        lat=37.4419,
        lng=-122.1419,
        markers=[(37.4419, -122.1419)]
    )
    sndmap = Map(
        identifier="sndmap",
        lat=37.4419,
        lng=-122.1419,
        markers=[
          {
             'icon': 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
             'lat': 37.4419,
             'lng': -122.1419,
             'infobox': "<b>Hello World</b>"
          },
          {
             'icon': 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
             'lat': 37.4300,
             'lng': -122.1400,
             'infobox': "<b>Hello World from other place</b>"
          }
        ]
    )
    return render_template('example.html', mymap=mymap, sndmap=sndmap)

if __name__ == "__main__":
    app.run(debug=True)
Map() Parameters
  • lat: The latitude coordinate for centering the map.
  • lng: The longitude coordinate for centering the map.
  • zoom: The zoom level. Defaults to 13.
  • maptype: The map type - ROADMAP, SATELLITE, HYBRID, TERRAIN. Defaults to ROADMAP.
  • markers: Markers array of tuples having (lat, lng, infobox, icon, label). Defaults to None.
  • or markers: a list of dicts containing lat, lng, infobox, icon, label.
  • or markers: Markers dictionary with icon urls as keys and markers array as values.
  • varname: The instance variable name.
  • style: A string containing CSS styles. Defaults to "height:300px;width:300px;margin:0;".
  • identifier: The CSS ID selector name.
  • cls: The CSS Class selector name. Defaults to "map".
  • language: The map language. Defaults to "en".
  • region: The map region. Defaults to "US".

Also controls True or False:

  • zoom_control
  • maptype_control
  • scale_control
  • scale_control
  • streetview_control
  • rotate_control
  • fullscreen_control
  • scroll_wheel
  • collapsible (map collapses by click on varname_collapse button)
  • mapdisplay (show a collapsible map by default or not)
  • center_on_user_location (using HTML5 Geolocation)

2. Template

<!DOCTYPE html>
<html>
  <head>
    {{"decoupled-map"|googlemap_js(37.4419, -122.1419, markers=[(37.4419,
    -122.1419)])}} {{mymap.js}} {{sndmap.js}}
  </head>
  <body>
    <h1>Flask Google Maps Example</h1>

    <h2>Template function centered, no marker</h2>
    {{googlemap("simple-map", 37.4419, -122.1419)}}

    <h2>Template filter decoupled with single marker</h2>
    {{"decoupled-map"|googlemap_html(37.4419, -122.1419)}}

    <h2>Template function with multiple markers</h2>
    {% with map=googlemap_obj("another-map", 37.4419, -122.1419,
    markers=[(37.4419, -122.1419), (37.4300, -122.1400)]) %} {{map.html}}
    {{map.js}} {% endwith %}

    <h2>First map generated in view</h2>
    {{mymap.html}}

    <h2>Second map generated in view</h2>
    <h3>Example for different icons in multiple markers with infoboxes</h3>
    {{sndmap.html}}
  </body>
</html>

Infobox

Here's an example snippet of code:

    Map(
        identifier="catsmap",
        lat=37.4419,
        lng=-122.1419,
        markers=[
            {
                'icon': 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
                'lat':  37.4419,
                'lng':  -122.1419,
                'infobox': "<img src='cat1.jpg' />"
            },
            {
                'icon': 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
                'lat': 37.4300,
                'lng': -122.1400,
                'infobox': "<img src='cat2.jpg' />"
            },
            {
                'icon': 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png',
                'lat': 37.4500,
                'lng': -122.1350,
                'infobox': "<img src='cat3.jpg' />"
            }
        ]
    )

Which results in something like the following map: screen shot 2015-07-29 at 2 41 52 pm

Label

Here's an example snippet of code:

Map(
        identifier="labelsmap",
        lat=37.4419,
        lng=-122.1419,
        markers=[
            {
                'lat': 37.4500,
                'lng': -122.1350,
                'label': "X"
            },
            {
                'lat':  37.4419,
                'lng':  -122.1419,
                'label': "Y"
            },
            {
                'lat': 37.4300,
                'lng': -122.1400,
                'label': "Z"
            }
        ]
    )

Which results in something like the following map:

Map showing markers with labels

Fit all markers within bounds

Allow users to easily fit all markers within view on page load

Without bounds

@app.route('/map-unbounded/')
def map_unbounded():
"""Create map with markers out of bounds."""
    locations = []    # long list of coordinates
    map = Map(
        lat=locations[0].latitude,
        lng=locations[0].longitude,
        markers=[(loc.latitude, loc.longitude) for loc in locations]
    )
    return render_template('map.html', map=map)

image

With bounds

@app.route('/map-bounded/')
def map_bounded():
"""Create map with all markers within bounds."""
    locations = []    # long list of coordinates
    map = Map(
        lat=locations[0].latitude,
        lng=locations[0].longitude,
        markers=[(loc.latitude, loc.longitude) for loc in locations],
        fit_markers_to_bounds = True
    )
    return render_template('map.html', map=map)

image

Geocoding and Reverse Geocoding

from flask_googlemaps import get_address, get_coordinates
API_KEY = 'YOUR API KEY'

#Reverse Geocoding: getting detailed address from coordinates of a location
print(get_address(API_KEY,22.4761596,88.4149326))
#output: {'zip': '700150', 'country': 'India', 'state': 'West Bengal', 'city': 'Kolkata', 'locality': 'Kolkata', 'road': 'Techno City', 'formatted_address': 'Sirin Rd, Mauza Ranabhutia, Techno City, Kolkata, West Bengal 700150, India'}


#Geocoding: getting coordinates from address text
print(get_coordinates(API_KEY,'Netaji Subhash Engineering College Kolkata'))
#output: {'lat': 22.4761596, 'lng': 88.4149326}

Run the example app

$ git clone https://github.com/flask-extensions/Flask-GoogleMaps
$ cd Flask-GoogleMaps/

If you have Poetry

$ poetry install

without poetry

$ pip install --upgrade pip
$ pip install -e .
$ pip install -r requirements.txt

Run it.

$ FLASK_GOOGLEMAPS_KEY="YourKeyHERE" FLASK_APP=examples/example.py flask run
running on localhost:5000 .....

Access: http://localhost:5000/ and http://localhost:5000/fullmap

Contribute with the Google Maps API

Please see this page developers.google.com/maps/documentation/javascript/tutorial and contribute!

flask-googlemaps's People

Contributors

alfredopironti avatar bernardoow avatar bhuveshsharma09 avatar chicao avatar essut avatar fao89 avatar getcake avatar gferioli0418 avatar herugrim avatar hona avatar jacobgeogeek avatar jcla490 avatar joshrosenhanst avatar juanvmarquezl avatar kjellreell avatar marcuxyz avatar mattdaviscodes avatar mebroadbent avatar michaelbukachi avatar mihxen avatar mjhea0 avatar nklever avatar riverfount avatar rochacbruno avatar ruanaragao avatar rubenrocha avatar skrstv123 avatar smallsea avatar thencar avatar tvgdb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flask-googlemaps's Issues

Erro de compatibilidade

Opa, @rochacbruno quando tentei instalar a extensรฃo foi retornado para mim um erro de compatibilidade com o SQLAlchemy. O erro foi o seguinte:

Collecting flask-googlemaps
  Using cached Flask_GoogleMaps-0.2.5-py2.py3-none-any.whl
Requirement already satisfied: flask in ./venv/lib/python3.5/site-packages (from flask-googlemaps) (0.12.2)
Requirement already satisfied: itsdangerous>=0.21 in ./venv/lib/python3.5/site-packages (from flask->flask-googlemaps) (0.24)
Requirement already satisfied: Jinja2>=2.4 in ./venv/lib/python3.5/site-packages (from flask->flask-googlemaps) (2.10)
Requirement already satisfied: Werkzeug>=0.7 in ./venv/lib/python3.5/site-packages (from flask->flask-googlemaps) (0.14.1)
Requirement already satisfied: click>=2.0 in ./venv/lib/python3.5/site-packages (from flask->flask-googlemaps) (6.7)
Requirement already satisfied: MarkupSafe>=0.23 in ./venv/lib/python3.5/site-packages (from Jinja2>=2.4->flask->flask-googlemaps) (1.0)
flask-sqlalchemy 2.3.2 has requirement Flask>=0.10, but you'll have flask GoogleMaps which is incompatible.
Installing collected packages: flask-googlemaps
Successfully installed flask-googlemaps

Diz que foi instalado com sucesso, mas na verdade nรฃo instala.

Unicode error on new version

I made a upgrade to the new version and i'm getting a JS error now:

`var raw_markers = [{'lat': u'-19.9520738', 'lng': u'-43.9490132', 'icon': '//maps.google.com/mapfiles/ms/icons/red-dot.png'}];``

You can see that it is including u in front of lat lng.

I checked in the source and it seems to be correct gmap.markers|tojson|safe , but when using pip install flask-googlemaps --upgrade it is not installing the same version that we have here.

Is something needed to update on pip? Maybe need to change the version? (from 0.2.2 to 0.2.3) ?

Style parameter non-responsive

I am invoking the Map class, trying to modify the style variable, but I'm not seeing any response in the output. Do you have any additional examples you could provide? My code below, any help would be appreciated!

From my app/init.py:

@app.route("/", methods=['POST','GET'])
def main():
	sndmap = Map(
		identifier="sndmap",
		lat=33.753746,
                lng=-84.386330,
                style="height:200px;width:200px:margin:0;",  # <---
                ....
                )
        return render_template('index.html', sndmap=sndmap)

From my html file:

<head>
    ....
    {{sndmap.js}}
</head>

<section>
    <center>
    {{sndmap.html}}
    <p></p>
    <ul class="actions">
        <li><a href="/learnmore" class="button alt">Learn More</a></li>
    </ul>
    </center>
</section>

Can we get the lat/long from user click?

I am trying to record the lat/long data from user click. JS can do it with something like:
google.maps.event.addListener(map, 'click', function(event) {placeMarker(map, event.latLng, marker);});

How can i pass the this "event.latLng" to the flask? Can we add this api to flask_googlemaps?

Filter option for markers

It will be nice to be able to filter by type of markers, example

Display:

  • Blue markers
  • Red markers
  • Green markers

Center map based on User's location?

I've been using Flask-GoogleMaps to display some companies that are partnering with us.

I would be great if we had a way to center the map based on user's location.
So then users could see easily all the markers around them.

For now, I'm using request.access_route to get user's IP/Location and then, set the lat and lng variables.

Wondering if it could be included in the next versions.

mymap undefined when put {{mymap.js}} on template head

Simple maps working good, same as the other maps which just need to put block of code directly on template file.
But the maps that need to put block of code on views & template files, don't work with error undefined mapname.
i.e. when I use mymap = Map (...) (views file), then put the {{mymap.js}} on template header and {{mymap.html}} on template body, it will turn out to error UndefinedError: 'mymap' is undefined.
Did I miss something? I have following the instructions on the front page, like registering maps to the __init__.py, importing maps into my views, put mymap=mymap in the return render_template() and so on.

Thank you.

windows?

Hi,

I try to use the sample on Windows and it doesn't work

Only linux?

Flask 0.7.2 not allowing GoogleMaps to init

I'm on Flask 0.7.2, and when I try to import 'flask-googlemaps' and add 'GoogleMaps(app)' , I receive a SIGTERM with the following error message:

'''
(env)macs-MacBook-Pro:facebook-template-python mac$ foreman start
03:17:33 web.1 | started with pid 2212
03:17:33 web.1 | Traceback (most recent call last):
03:17:33 web.1 | File "exampleapp.py", line 158, in
03:17:33 web.1 | GoogleMaps(app)
03:17:33 web.1 | File "/Users/mac/Dropbox/development/facebook-template-python/env/lib/python2.7/site-packages/flask_googlemaps/init.py", line 57, in init
03:17:33 web.1 | self.init_app(app)
03:17:33 web.1 | File "/Users/mac/Dropbox/development/facebook-template-python/env/lib/python2.7/site-packages/flask_googlemaps/init.py", line 62, in init_app
03:17:33 web.1 | app.add_template_filter(googlemap_html)
03:17:33 web.1 | AttributeError: 'Flask' object has no attribute 'add_template_filter'
03:17:33 web.1 | exited with code 1
03:17:33 system | sending SIGTERM to all processes
SIGTERM received
'''

Documentation about map.js and map.html in templates is missing

I need some help, In my project i used the normal kind of templating with a default layout and every other extends this.

  • When adding a map to lets say a profile.html which extends layout.html, how can i add mymap.js to the <head> tag if this profile page does not have a head, only the one from the layout?
  • If i add this mymap.js to the layout, my pages will definitely crash because i am sending this resource only from the profile app context.

Do you have a special way for this situation or is there a workaround?

Thank you.

Making embedded maps bootstrap responsive

Is there a way to alter a map object to make it bootstrap responsive?

Right now I use the following block in my html template:

{% with map=googlemap_obj("my-map", lat=user_lat, lng=user_lng, markers=user_markers, zoom=16, style="height:900px;width:900px;") %}
{{map.html}}
{{map.js}}
{% endwith %}

custom markers not showing up

Hello,

First, thanks a lot, it is a very good addition to Flask

I am trying to use the custom markers, and they never show up, even if i use your example or other pictures. I don't see any errors showing up in flask or the python console

Thanks

Develop better demo application

The demo app is in https://github.com/rochacbruno/Flask-GoogleMaps/tree/master/examples

Accessible in: http://flaskgooglemaps.pythonanywhere.com

The page currently is very simple and needs improvements.

  • Better layout (simple, yet beautiful) (example: https://jz6.github.io/PoGoMap/ )
  • A menu bar to handle project links (repo, chat, issues etc)
  • mobile enabled (responsive)
  • split the demo into different views (one per map with links in menu bar)
  • Put better code example below each map, with (html + python) tabs and code highlight (maybe using embedded gist)
  • A section "who uses fgmaps" including https://github.com/AHAAAAAAA/PokemonGo-Map
  • Include Flask-Caching in demo app views

marker

Hi,

in fullmap I want pass a series of markers lat long extract from mydatabase, but I don't understand How can I pass the list of dict.

like for m in lista_co:
appo=[
{
'icon': '//maps.google.com/mapfiles/ms/icons/green-dot.png',
'lat': m['lat'],
'lng': m['long'],
'infobox': "Questo e' un marker di prova"
}]
markers.append(appo)
I want pass markers to Map ()...

Issue adding API key and scroll_wheel

Currently I need to use the standart script line proposed by google. If I dont use this I get an error No-Key-Error and the map doesnt show:
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&signed_in=true&libraries=places"></script>

It seems that these have no effect, because if I remove the script line I get again the No-Key-Error:

GoogleMaps(app, key="MYKEY")

or in my config.py

GOOGLEMAPS_KEY = "MYKEY"

So currently I need to use both, the mymap.js and the script line, which lead to "You have included the Google Maps API multiple times on this page" but still works. Also I cant disable the scroll_wheel. I am setting up the map in python:

mymap = Map(
    identifier="view-side",
    lat=location.latitude,
    lng=location.longitude,
    infobox=[],
    markers=[],
    scroll_wheel = False,
    zoom = 11
)

The scroll_wheel = False does not do anything here, eventhough I found it in the documentation.

Initial Update

Hi ๐Ÿ‘Š

This is my first visit to this fine repo, but it seems you have been working hard to keep all dependencies updated so far.

Once you have closed this issue, I'll create seperate pull requests for every update as soon as I find one.

That's it for now!

Happy merging! ๐Ÿค–

Infobox hover and persist on click

Add option to show infobox on hover and persist on click.

Example

                    if (item["infobox"]) {
                        (function(_infobox, _map, _marker){
                            _marker.infoWindow = new google.maps.InfoWindow({
                                content: _infobox
                            });
                            _marker.addListener('click', function() {
                                _marker.infoWindow.open(_map, _marker);
                                _marker["persist"] = true;
                            });
                            google.maps.event.addListener(_marker.infoWindow,'closeclick',function(){
                               _marker["persist"] = null;
                            });
                            _marker.addListener('mouseover', function() {
                                _marker.infoWindow.open(_map, _marker);
                            });
                            _marker.addListener('mouseout', function() {
                                if (!_marker["persist"]) {
                                    _marker.infoWindow.close();
                                }
                            });
                        })(item["infobox"], map, marker);
                    }

jinja2.exceptions.TemplateNotFound: googlemaps/gmapjs.html

Not sure if this is an issue with Flask-Googlemaps or just human error. I am currently using the library on an app deployed on Heroku, and now see the following error when I try to load a page where I am calling Flask-Googlemaps.

2018-03-20T15:05:30.959296+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/flask_googlemaps/__init__.py", line 703, in render
2018-03-20T15:05:30.959297+00:00 app[web.1]:     return render_template(*args, **kwargs)
2018-03-20T15:05:30.959299+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/flask/templating.py", line 133, in render_template
2018-03-20T15:05:30.959301+00:00 app[web.1]:     return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
2018-03-20T15:05:30.959302+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/flask/templating.py", line 57, in get_source
2018-03-20T15:05:30.959304+00:00 app[web.1]:     return self._get_source_fast(environment, template)
2018-03-20T15:05:30.959306+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/flask/templating.py", line 85, in _get_source_fast
2018-03-20T15:05:30.959308+00:00 app[web.1]:     raise TemplateNotFound(template)
2018-03-20T15:05:30.959393+00:00 app[web.1]: jinja2.exceptions.TemplateNotFound: googlemaps/gmapjs.html

I recently changed the app from having a single "journal.py" module which contained everything (routes, config stuff, models) to one where all this was spread across multiple modules. Previously my app looked like this...

/journal
    journal.py
    Procfile
    requirements.txt
    runtime.txt
    /templates
    /static

Now it looks like this....

/journal
    /app
        __init__.py
        models.py
        routes.py
        config.py
        /templates
        /static
    journal.py
    Procfile
    requirements.txt
    runtime.txt

I have confirmed that I am using the latest version (0.2.5).

This is an awesome tool. It has really made my life easy. Thanks for making it available to the community.

Infobox: Only accepting single item from list.

  • 1. I have a list filled with text, ie ['text1', 'text2', 'text3']
  • 2. If I use only one item from the list with the infobox parameter then, as expected, an infobox containing that single text is attached to each marker.
  • 3. However, if I use the entire list with the infobox parameter, the map doesn't load at all.

See my code from views.py

@app.route('/')
@app.route('/index', methods=['GET', 'POST'])
@login_required
def index():
    coords = pickle.load(open("coordinates.p", "rb"))
    addresses = pickle.load(open("addresses.p", "rb"))
    mymap = Map(
        identifier="view-side",
        style="height:100%; width:100%; left:0; position:absolute;z-index:200;",
        lat=coords[0][0],
        lng=coords[0][1],
        zoom='5',
        infobox=addresses,  # does not work, but if I change it to addresses[0] it works with out issue
        markers=coords
    )
    return render_template('index.html', mymap=mymap)

Question: large dataset loading.

Hey!
I am using Flask-googleMaps for a NASA Space Apps Challenge and its been working great so far, thanks for making it! I have hit one issue I was hoping to pick your mind about and see if you have a solution.

I am tring to render over 20k +/- circles on the map to show wildfires detected by satellite. I believe I implemented FGM properly but it takes forever to load. I think this is because of the very large dataset I am loading.

Do you have any ideas for ways that I can either stream the circles in over time or something else that will work to load them?

Ploting data from mysql DB.

Hello
how can i inject data from mysql to maps, i use this code but its not working:

users = User.query.all()
fullmap = Map(
           identifier="fullmap",
           varname="fullmap",
           style=(
               "height:100%;"
               "width:100%;"
               "top:0;"
               "left:0;"
               "position:absolute;"
               "z-index:10;"               
           ),
            
           lat=37.4419,
           lng=-122.1419,           
            
           markers=[
               {           
                   'icon': 'static/img/icons/home1.png',
                   'title': 'Adresse Home',
                   'lat': user.latitude,
                   'lng': user.longitude,
                   'infobox': (
                       "Hello I am <b style='color:#ffcc00;'>YELLOW</b>!"
                       "<h3>"user.first_name"</h3>"
                       "<img src='user.image'>"
                       "<br>Images allowed!"
                   )
               }for user in users:],

Can you help me please. Thank you

Allow for two finger zoom

This would make things a lot more convenient for laptop users. I'm not sure how hard it is to code, but the feature would make for a huge improvement.

Infobox for multple icons

When you have multiple icons, you can't set different infoboxes for each icon.

In the initialize_ function in gmapsj.html, the getInfoCallback({{gmap.varname}}, "{{gmap.infobox[loop.index0]|safe}}")) is inside the markers[icon] loop:

      {% for icon in gmap.markers %}
            {% for marker in gmap.markers[icon] %}
                var marker_{{loop.index0}} = new google.maps.Marker({
                    position: new google.maps.LatLng({{marker.0}}, {{marker.1}}),
                    map: {{gmap.varname}},
                    icon: "{{ icon }}"
                });
                {% if gmap.infobox != None %}
                        {% if gmap.typeflag %}
                            google.maps.event.addListener(marker_{{loop.index0}}, 'click',
                            getInfoCallback({{gmap.varname}}, "{{gmap.infobox[loop.index0]|safe}}"));
                        {% else %}
                            google.maps.event.addListener(marker_{{loop.index0}}, 'click',
                            getInfoCallback({{gmap.varname}}, "{{gmap.infobox|safe}}"));
                        {% endif %}
                {% endif %}
            {% endfor %}
        {% endfor %}

In the case where you have one marker per icon and a infobox list, you always get the first value of the list for every marker.

It's not clear to me what's the best way to add multiple infoboxes for multiple icons without breaking the multiple infoboxes for multiple markers with one icon. Maybe a flag multipleiconflag and a call to getInfoCallback outside the marker loop?

Marker Labels?

Does this module provide the ability to add labels to markers placed on the map?

distance support?

Hi Guys,

I was searching for google maps API and found this. really like Flask_GoogleMaps. Is there any support for Distance Matrix?

Thanks

How to get a reference to the map in the html

I'm rendering this map

map = Map(
        identifier='map',
        style='height:100%;width:100%;top:0;left:0;position:absolute;z-index:200;',
        lat=deflat,
        lng=deflng,
        markers=markers,
        zoom='15', )
    return render_template('map.html', mymap=map)

and in the html

{{mymap.js}}

Now I want to add markers dynamically to this map with jQuery like

var marker = new google.maps.Marker({
    position: myLatlng,
    title:"Hello World!"
});

// To add the marker to the map, call setMap();
marker.setMap(map);

so I need a reference to this map object in the page, so how?

Places API

by @macgngsta in https://github.com/AHAAAAAAA/PokemonGo-Map/issues/396

As awesome as Flask-GoogleMaps is in creating a quick google map, there is no support for other google apis, such as places API

https://developers.google.com/maps/documentation/javascript/examples/places-searchbox

i actually tried to get a search box in, but it requires loading the places library after the google key, and i think that without some significant effort on adding to the flask-googlemaps project or making a short term hack would be the only way

there also could be a possibility of going openstreet maps instead of google maps.

So I think this is one easy thing to add

Bad setup.py in 0.2.5

0.2.4 is fine, regression occurs at 0.2.5

Repro is easy:

pip install -v flask-googlemaps

Tidbit you're interested in is

Installing collected packages: Werkzeug, MarkupSafe, Jinja2, click, itsdangerous, flask, flask-googlemaps

  Compiling /private/var/folders/2h/0dr8jftd1916yq_lp40__wzh0000gn/T/pip-build-avapA_/Jinja2/jinja2/asyncfilters.py ...
    File "/private/var/folders/2h/0dr8jftd1916yq_lp40__wzh0000gn/T/pip-build-avapA_/Jinja2/jinja2/asyncfilters.py", line 7
      async def auto_to_seq(value):
              ^
  SyntaxError: invalid syntax

  Compiling /private/var/folders/2h/0dr8jftd1916yq_lp40__wzh0000gn/T/pip-build-avapA_/Jinja2/jinja2/asyncsupport.py ...
    File "/private/var/folders/2h/0dr8jftd1916yq_lp40__wzh0000gn/T/pip-build-avapA_/Jinja2/jinja2/asyncsupport.py", line 22
      async def concat_async(async_gen):
              ^
  SyntaxError: invalid syntax

Impact to user is when you do pip freeze it won't show Flask-GoogleMaps==0.2.5

The error is coming from Jinja but pip install Flask still causes Flask to show up in pip freeze, so something is wrong with the setup.py

Dynamically change center

Hi,

I can't find an example so I try this code but can't change the center position:

movingmap_markers.map(function(mk){mk.setCenter({lat: 37.44, lng:-122.135})})

Regards,

Feature request: Export map object to window

This issue is related to #27

function initialize_{{gmap.varname}}() {
               var {{gmap.varname}} = new google.maps.Map(
                         document.getElementById('{{gmap.identifier}}') )
       //...

Please add an option to export the var {{gmap.varname}} as a window var like

var {{gmap.varname}} = new google.maps.Map(
                         document.getElementById('{{gmap.identifier}}') )
window[{{gmap.varname}}]={{gmap.varname}}

In this way it will be possible to add markers from the page like

var marker = new google.maps.Marker({
    position: myLatlng,
    title:"Hello World!"
});

// To add the marker to the map, call setMap();
marker.setMap(window.map);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.