У меня есть код js, который используется для отображения карты Google на некоторых страницах, когда я хотел начать использовать barbajs (pjax), все было нормально, пока я не проверил, что мой код выполняются много раз в зависимости от того, сколько раз я посетил данную страницу, например:JS, код выполняется несколько раз из-за (barbajs) Pjax
, когда я посещаю http://example.com/regions
Барб является fething моей страницы, которая содержит HTML и JS код и выполнить его, второй, когда я посещаю http://example.com/regions2
и есть аналогичный код и в консоли я получил информацию о том, что мой js-код выполняется дважды, когда я снова заходил в http://example.com/regions
, код был отменен 3 раза и так далее. Я думаю, причина в том, что мой код js находится в памяти браузера, если это так, как я проверяю его присутствие? Или как сделать этот код один раз?
Мой код выглядит расслоение плотной, как это в двух словах:
Barba.Dispatcher.on('transitionCompleted', function() {
var mapDistributors = mapDistributors || {
makeMap: function() {
var loc = this.location.split(','),
pos = new google.maps.LatLng(loc[0], loc[1]);
var countryCenter = new google.maps.LatLng(59.9882184, 18.2516778);
var mapOptions = {
zoom: 6,
center: countryCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.mapObj = new google.maps.Map(document.querySelector('.mapGoogleDistributors'), mapOptions);
this.destination = pos;
var marker = new google.maps.Marker({
position: pos,
icon: 'icon.svg',
info: {
}
})
this.markers.push(marker);
},
handleRoute: function(result, status) {
if (status != google.maps.DirectionsStatus.OK || !result.routes[0]) {
alert('wrong data entered!');
return false;
}
this.pathRender.setDirections(result);
this.formInput.value = result.routes[0].legs[0].start_address;
},
prepareRoute: function(coords) {
var renderOptions = {
mapDistributors: this.mapObj,
polylineOptions: {
strokeColor: '#ff0000',
strokeWeight: 4,
strokeOpacity: 0.8
},
suppressMarkers: true
}
this.pathRender.setOptions(renderOptions);
var pathData = {
origin: coords ? coords : this.formInput.value,
destination: this.destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
}
this.path.route(pathData, this.handleRoute.bind(this))
},
getGeoData: function() {
navigator.geolocation.getCurrentPosition(
function(position) {
this.prepareRoute(position.coords.latitude + "," + position.coords.longitude);
}.bind(this),
function(errorObj) {
alert('error!');
}, {
enableHighAccuracy: true
}
);
},
checkGeoSupport: function() {
if (navigator.geolocation) {
var findPositionButton = document.querySelector('#findButton');
findPositionButton.classList.remove('hidden');
findPositionButton.onclick = function(e) {
e.preventDefault();
this.getGeoData();
}.bind(this);
}
},
init: function(options) {
if (!options.location) return;
Barba.Dispatcher.on('transitionCompleted', this.makeMap.bind(this));
Barba.Dispatcher.on('transitionCompleted', this.markersLocation.bind(this));
// try { google.maps.event.addDomListener(window, "load", this.makeMap.bind(this)); } catch(e) {return; };
// try { google.maps.event.addDomListener(window, "load", this.markersLocation.bind(this)); } catch(e) {return; };
// try { google.maps.event.addDomListener(window, "load", this.showInfo.bind(this)); } catch(e) {return; };
this.options = options;
this.location = this.options.location;
this.form = document.querySelector('.mapForm');
this.formInput = document.querySelector('.inputMap');
this.path = new google.maps.DirectionsService();
this.pathRender = new google.maps.DirectionsRenderer();
console.log(this, document.querySelector('.mapForm'));
this.form.onsubmit = function(e) {
e.preventDefault();
var address = document.querySelector('#search').value;
this.getLatLng(address, 6);
}.bind(this);
this.checkGeoSupport();
},
// markers
placeMarker: function(distrybutors, instalators) {
for (var i = 0; i < distrybutors.length; i++) {
var d = distrybutors[i];
var latlng = new google.maps.LatLng(d.latLng[0], d.latLng[1]);
var marker = new google.maps.Marker({
// map: this.mapObj,
position: latlng,
icon: '/bundles/galmetmap/images/galmet_sygnet.svg',
info: {
name: d.name,
address: d.address,
phone: d.phone
}
});
this.addInfo(marker);
this.markers.push(marker);
}
this.mapClustering();
},
markers: [],
htmlInfo: function(info) {
},
//find markers
findClosest: function(position, markersToReturn) {
var positionAddress = new google.maps.LatLng(position.lat(), position.lng());
var closest = [];
var counter = 0;
mapDistributors.mapObj.setCenter(positionAddress);
mapDistributors.mapObj.setZoom(11);
for (var i = 0; i < mapDistributors.markers.length; i++) {
var marker = mapDistributors.markers[i];
var distance = mapDistributors.calcDistance(marker.position, positionAddress);
if (distance <= 150) {
var obj = {
distance: distance,
info: marker.info
}
closest.push(obj);
}
}
var chunkClosest = closest.sort(function(a, b) {
return a.distance - b.distance;
});
var results = document.querySelector('.result');
results.innerHTML = '';
for (var i = 0; i < markersToReturn; i++) {
var distance = document.createElement('div');
distance.innerHTML = 'Odległość w km ' + chunkClosest[i].distance;
var instalator = mapDistributors.htmlInfo(chunkClosest[i].info);
instalator.appendChild(distance);
results.appendChild(instalator);
}
window.location.href = "#result";
},
calcDistance: function(position1, position2) {
return (google.maps.geometry.spherical.computeDistanceBetween(position1, position2)/1000).toFixed(2);
},
addInfo: function(marker) {
marker.addListener('click', function() {
var infowindow = new google.maps.InfoWindow({
content: mapDistributors.htmlInfo(marker.info),
});
infowindow.open(mapDistributors.mapObj, marker);
})
},
geocoder: new google.maps.Geocoder(),
getLatLng: function(address, markersToReturn) {
mapDistributors.geocoder.geocode({
'address': address
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
mapDistributors.findClosest(results[0].geometry.location, markersToReturn);
} else {
alert('reason : ' + status);
}
})
},
mapClustering: function() {
var mcOptions = {
imagePath: 'https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/images/m'
};
this.cluster = new MarkerClusterer(this.mapObj, this.markers, mcOptions);
},
markersLocation: function() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var jsonData = JSON.parse(xmlHttp.responseText);
if (jsonData.status) {
this.placeMarker(jsonData.distrybutors, jsonData.instalators);
} else {
console.log('error');
}
}
}.bind(this)
xmlHttp.open("GET", document.querySelector('#urlAdress').value, true); // true for asynchronous
xmlHttp.send();
},
}
mapDistributors.init({
location: "50.1943227,7.8434933"
});