OpenCageData / leaflet-opencage-geocoding

A Leaflet geocoding control that uses the OpenCage geocoding API
BSD 2-Clause "Simplified" License
22 stars 11 forks source link

Remote activation #11

Closed flightsurvey closed 7 years ago

flightsurvey commented 7 years ago

I have adapted the code so that the container, form and input now have IDs:


onAdd: function (map) {
    var className = 'leaflet-control-ocd-search';
    var container = L.DomUtil.create('div', className);
    container.id = "searchContainer";
    var icon = L.DomUtil.create('div', 'leaflet-control-ocd-search-icon', container);
    var form = this._form = L.DomUtil.create('form', className + '-form', container);
    form.id="openCageForm";
    var input;

    this._map = map;
    this._container = container;
    input = this._input = L.DomUtil.create('input');
    input.id = "openCageSearchInput";
    input.type = 'text';
    input.autocomplete = "off";
    input.placeholder = this.options.placeholder;

    L.DomEvent.addListener(input, 'keydown', this._keydown, this);

Which results in:

<div class="leaflet-control-ocd-search leaflet-control" id="searchContainer">
    <div class="leaflet-control-ocd-search-icon"></div>
        <form class="leaflet-control-ocd-search-form" id="openCageForm">
            <input class="" id="openCageSearchInput" type="text" autocomplete="off" placeholder="search for ...">
            <div class="leaflet-control-ocd-search-form-no-error" id="searchButton">Nothing found.</div>
        </form>
    </div>
</div>

I am using standard jquery to add the "leaflet-control-ocd-search-expanded" class to the container and populate the input from a value in another form:

$('#openCageSearchInput').val(nl2space($('#newAssignmentAddress').val()));
$('#searchContainer').addClass("leaflet-control-ocd-search-expanded");

Which works OK but, despite trying to force a form submit and simulating keypress (enter) on the input, I cannot get the search to activate.

Do you have an idea as to how it could be done?

Many thanks

mtmail commented 7 years ago

It seems the jQuery form_element.submit() causes a page reload.

Below a non-jQuery solution

Open http://rawgit.com/opencagedata/leaflet-opencage-search/master/demo/index.html in Google Chrome and open the developer console

// opens the search field
document.querySelector('.leaflet-control-ocd-search-icon').click();
// fills the search field
document.querySelector('.leaflet-control-ocd-search-form input').setAttribute('value','Notting Hill');
// submits the form
var submit_event = document.createEvent('HTMLEvents');
submit_event.initEvent('submit', true, false);
document.querySelector('.leaflet-control-ocd-search-form').dispatchEvent(submit_event);
flightsurvey commented 7 years ago

Perfect! Worked first time - you are a star.