2017-02-18 1 views
0

Я использую django 1.10.5, booststrap 4.0 и LeafletJs 1.0.3 с плагином для маршрутизации и геокодером. Теперь у меня есть следующая проблема: кнопка свернуть панели управления для машины маршрутизации не загружается (ее не отображается в html-коде), когда карта больше 640 x 640 пикселей, когда страница загружается в первый раз. map bigger than 600x600px and no collapse button Map 500x500px with collapse button visible проблем нет, когда я делаю карту больше с помощью инструментов chrome dev после того, как страница полностью загружена с размером карты, установленной в css до 640x640px или меньше.Leafletjs Кнопка ручного пуска машины кнопка не загружается

У меня есть версия, которая работает так, как должна, но это без джанго и бутстрапа, и мне нужно, чтобы она работала с обоими.

CSS код

.map-add-size{ 
    position: relative; 
    width: 500px; 
    height:500px; 
} 

.html

{% extends 'base.html' %} 
{% load static %} 
{% load crispy_forms_tags %} 
{% block css %} 
    <link href="{% static 'routes/css/add.css' %}" rel="stylesheet"> 
    {{block.super}} 
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"> 
    <link href="{% static 'routes/css/leaflet-routing-machine.css' %}" rel="stylesheet" > 
    <link href="{% static 'routes/css/Control.Geocoder.css' %}" rel="stylesheet"> 

{% endblock %} 

{% block content %} 

    <h3>Add a new route</h3> 
     <div class="row"> 
     <div class="route-edit"> 
      <div class="col-xs-6"> 
      <p>Route page information</p> 
      <form id="mainForm" method="post" class="form"> 
       {% csrf_token %} 
       {{ routeAddForm|crispy }} 
       <div class="row route-edit"> 
        <button type="submit" name="save_route" class="btn btn-primary">Save and continue</button> 
       </div> 
      </form> 
     </div> 
     </div> 
    </div> 
    <div class ="row"> 
     <div class="cols-xs-8 map-container-div"> 
     <p>Add start and end markers by left clicking on the map. <br> 
      Add markers by clicking on the lines inbetween the start and end markers<br> 
      Remove markers by clicking on the cross next to the address of the marker. 
     </p> 
     </div> 
    </div> 
    <div id="map-add" class="map-add-size"></div> 
{% endblock %} 

{%block javascript %} 
{{block.super}} 
<script src="{% static 'routes/js/cookie.js' %}"></script> 
<script> 
var csrftoken = Cookies.get('csrftoken'); 
</script> 
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script> 
<script src="{% static 'routes/js/leaflet-routing-machine.js' %}"></script> 
<script src="{% static 'routes/js/Control.Geocoder.js' %}"></script> 
<script src="{% static 'routes/js/map-add.js' %}"></script> 
{%endblock%} 

Javascript

window.lrmConfig = { 
// serviceUrl: 'https://api.mapbox.com/directions/v5', 
// profile: 'mapbox/driving', 
}; 

var map = L.map('map-add').setView([51.505, -0.09], 3); 

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}{r}.png', { 
    attribution: '© OpenStreetMap contributors' 
}).addTo(map); 


var geocoder = L.Control.Geocoder.mapzen('search-DopSHJw'), 
    control2 = L.Control.geocoder({ 
    geocoder: geocoder, 
    defaultMarkGeocode: false 
    }).on('markgeocode', function(e){ 
    var bbox = e.geocode.bbox; 
      var poly = L.polygon([ 
       bbox.getSouthEast(), 
       bbox.getNorthEast(), 
       bbox.getNorthWest(), 
       bbox.getSouthWest() 
      ]).addTo(map); 
      map.fitBounds(poly.getBounds()); 
    }).addTo(map); 

control = L.Routing.control(L.extend(window.lrmConfig, { 
    geocoder: L.Control.Geocoder.nominatim(), 
    routeWhileDragging: true, 
    reverseWaypoints: true, 
    showAlternatives: true, 
    altLineOptions: { 
     styles: [ 
      {color: 'black', opacity: 0.15, weight: 9}, 
      {color: 'white', opacity: 0.8, weight: 6}, 
      {color: 'blue', opacity: 0.5, weight: 2} 
     ] 
    }, 
})).addTo(map); 


L.Routing.errorControl(control).addTo(map); 

function createButton(label, container) { 
    var btn = L.DomUtil.create('button', '', container); 
    btn.setAttribute('type', 'button'); 
    btn.innerHTML = label; 
    return btn; 
} 

map.on('click', function(e) { 
    var container = L.DomUtil.create('div'), 
     startBtn = createButton('Start from this location', container), 
     destBtn = createButton('Go to this location', container); 

    var removeContainer = L.DomUtil.create('div'), 
    removeBtn = createButton('Remove waypoint',removeContainer); 

    L.popup() 
     .setContent(container) 
     .setLatLng(e.latlng) 
     .openOn(map); 

      L.DomEvent.on(startBtn, 'click', function() { 
     control.spliceWaypoints(0, 1, e.latlng); 
     map.closePopup(); 
    }); 

     L.DomEvent.on(destBtn, 'click', function() { 
     control.spliceWaypoints(control.getWaypoints().length - 1, 1, e.latlng); 
     map.closePopup(); 
    }); 

}); 

// Submit post on submit 
$('#mainForm').on('submit', function(event){ 
    event.preventDefault(); 
    console.log("form submitted!"); // sanity check 
    postData(); 
}); 

var successText; 
function postData(){ 
    console.log("postData is working!");// sanity check 
    var formData = $("#mainForm").serializeArray(); 

    var routeArray =Array(), 
    routeArray = control.getWaypoints(); 

    var json_obj = JSON.stringify(routeArray); 

    formData.push({name:'json_data',value:json_obj}); 
    console.log("form data that is send") 
    console.log(formData); 
    $.post({ 
     type: 'POST', 
     url: '/routes/add/', 
     data: formData, 
    }); 
} 

ответ

1

Я нашел способ, чтобы заставить его работать на больших размеров, чем 640 х. Я не уверен, что это правильный способ его исправить, но сейчас он работает.

в листовой-routing-machine.js в этой строке изменился с 640 до 1200, и теперь кнопка работает для карт размером более 640 пикселей.

collapsible = collapsible || (collapsible === undefined && map.getSize().x <= 1200); 
Смежные вопросы