1

Using django-map-widget to render a map widget in forms. it works fine, but...

I want to trigger the map in two ways (dynamically via javascript):

  1. trigger to re-center map on x,y
  2. trigger to add a marker to map on x,y

I tried so many ways, but i can't solve it.

You can see and play with my form here

Here are one of my attempts:

var locationRio = {lat: -22.915, lng: -43.197};
var marker = new google.maps.Marker({
  position: locationRio,
  map: $("#location-map-elem").map,
  title: 'Hello World!'
});

I am 90% sure my error is this part: $("#location-map-elem").map

Thanks in advance :)

1 Answers1

0

You need to access google map object for this. The accessing map object feature doesn't release yet. So, you need to install django-map-widgets directly from the master branch.

pip install git+git://github.com/erdem/django-map-widgets.git@master

Check this pull-request for more info.

After you installed the latest version, you will able to play with the Google Map JS API.

// re-center your marker 
var map = $('your-map-element').data(map);
var bounds = new google.maps.LatLngBounds();
bounds.extend(your_marker.getPosition());
map.fitBounds(bounds);
  • i tried this: var map = $('#location-map-elem').data(map); var marker = new google.maps.Marker({ position: {lat: 57.0230, lng: 10.087}, map: map, draggable: true }); var bounds = new google.maps.LatLngBounds(); bounds.extend(marker.getPosition()); map.fitBounds(bounds); i get these errors: InvalidValueError: setMap: not an instance of Map; and not an instance of StreetViewPanorama Uncaught TypeError: map.fitBounds is not a function – Michael Lind Feb 28 '18 at 10:44
  • That snippet code could be wrong, did you check google map JS documentation for re-centring? As I know, you should able to re-center the map after you got the `map` JS instance. – Erdem Ozkol Feb 28 '18 at 11:02
  • @MichaelLind I tested the code snippet and it worked for me, check the Google Map documentation. – Erdem Ozkol Feb 28 '18 at 14:25
  • https://github.com/erdem/django-map-widgets/blob/18e0d592ae7afea9aadadbb30d383bdd573b2de8/mapwidgets/static/mapwidgets/js/mw_google_point_field.js#L53 https://github.com/erdem/django-map-widgets/blob/18e0d592ae7afea9aadadbb30d383bdd573b2de8/mapwidgets/static/mapwidgets/js/mw_google_point_field.js#L79 These methods could be an example for your case. Check the these and implement with your `map` object instead of `this.map`. Thanks – Erdem Ozkol Mar 01 '18 at 13:40
  • thank you. but problem is that map is undefined. var map = $('your-map-element').data(map); for me it makes no sense, cause map, in the sentences, is undefined. maybe im blind or stupid, sorry, but i still cant see how this can be done. im giving up. moving on with another widget – Michael Lind Mar 02 '18 at 23:33
  • @MichaelLind this selector works for me: var map = $('.mw-map').data('map'); – Erik Telepovský Mar 28 '18 at 19:46