jQuery(document).ready(function($) { console.log('Distance Calculator script initialized'); // Check if required variables are available if (typeof dcp_vars === 'undefined') { console.error('dcp_vars is not defined'); return; } // Check if Leaflet is loaded if (typeof L === 'undefined') { console.error('Leaflet library is not loaded'); return; } // Store map instances const mapInstances = {}; // Destroy existing map instance function destroyMap(mapId) { if (mapInstances[mapId]) { mapInstances[mapId].remove(); mapInstances[mapId] = null; } } // Format time from hours to readable format function formatTime(hours) { const h = Math.floor(hours); const m = Math.round((hours - h) * 60); if (h === 0) { return `${m} min`; } else if (m === 0) { return `${h} hr`; } else { return `${h} hr ${m} min`; } } // Calculate travel times function calculateTravelTimes(distanceKm) { const speeds = { air: 900, // km/h (commercial flight) train: 100, // km/h (high-speed rail) road: 80 // km/h (highway driving) }; const times = {}; for (const mode in speeds) { const timeHours = distanceKm / speeds[mode]; times[mode] = formatTime(timeHours); } return times; } // Get setting value considering shortcode override function getSettingValue(settingName) { // Check if shortcode attribute overrides the setting if (typeof dcp_shortcode_atts !== 'undefined' && dcp_shortcode_atts[settingName] !== null) { return dcp_shortcode_atts[settingName] === 'true'; } // Return default setting return dcp_vars[settingName]; } // Calculate distance and display results function calculateDistance(from, to, showLoading = true) { const $button = $('#dcp-calculate'); if (!from || !to) { alert('Please enter both locations'); return; } // Show loading state if (showLoading) { $button.addClass('loading').prop('disabled', true); } $.ajax({ url: dcp_vars.ajax_url, type: 'POST', data: { action: 'calculate_distance', from: from, to: to }, success: function(response) { console.log('AJAX success:', response); if (response.success) { const data = response.data; const distanceKm = data.distance.toFixed(2); const distanceMiles = (data.distance * 0.621371).toFixed(2); // Show result container $('#dcp-result').show(); // Populate summary text if enabled if (getSettingValue('show_summary')) { $('#dcp-summary-container').show(); $('#dcp-summary-from').text(data.coords_from.display_name); $('#dcp-summary-to').text(data.coords_to.display_name); $('#dcp-summary-distance-km').text(distanceKm); $('#dcp-summary-distance-miles').text(distanceMiles); } else { $('#dcp-summary-container').hide(); } // Set distance value in the original location $('#dcp-distance-value').text(`${distanceKm} km (${distanceMiles} miles)`); // Show/hide travel time table if (getSettingValue('show_travel_time')) { $('#dcp-travel-time-container').show(); // Calculate and display travel times const travelTimes = calculateTravelTimes(data.distance); $('#dcp-time-air').text(travelTimes.air); $('#dcp-time-train').text(travelTimes.train); $('#dcp-time-road').text(travelTimes.road); } else { $('#dcp-travel-time-container').hide(); } // Populate location details $('#dcp-from-name').text(data.coords_from.display_name); $('#dcp-from-coords').text(`${data.coords_from.lat.toFixed(6)}, ${data.coords_from.lon.toFixed(6)}`); $('#dcp-from-lat').text(data.coords_from.lat.toFixed(6)); $('#dcp-from-lon').text(data.coords_from.lon.toFixed(6)); $('#dcp-from-country').text(data.coords_from.country || 'N/A'); $('#dcp-to-name').text(data.coords_to.display_name); $('#dcp-to-coords').text(`${data.coords_to.lat.toFixed(6)}, ${data.coords_to.lon.toFixed(6)}`); $('#dcp-to-lat').text(data.coords_to.lat.toFixed(6)); $('#dcp-to-lon').text(data.coords_to.lon.toFixed(6)); $('#dcp-to-country').text(data.coords_to.country || 'N/A'); // Show/hide features based on settings if (getSettingValue('show_route_map')) { $('#dcp-route-map-container').show(); setTimeout(function() { initMainMap(data.coords_from, data.coords_to); }, 100); } else { $('#dcp-route-map-container').hide(); } if (getSettingValue('show_from_map')) { $('#dcp-from-result-map').show(); setTimeout(function() { initLocationMap('dcp-from-result-map', data.coords_from, 'From Location'); }, 200); } else { $('#dcp-from-result-map').hide(); } if (getSettingValue('show_to_map')) { $('#dcp-to-result-map').show(); setTimeout(function() { initLocationMap('dcp-to-result-map', data.coords_to, 'To Location'); }, 300); } else { $('#dcp-to-result-map').hide(); } // Show/hide table fields based on settings if (getSettingValue('show_location_table')) { $('#dcp-from-table-container, #dcp-to-table-container').show(); // GPS Coordinates if (dcp_vars.show_gps_coordinates) { $('.dcp-gps-coordinates-header, .dcp-gps-coordinates-cell').show(); } else { $('.dcp-gps-coordinates-header, .dcp-gps-coordinates-cell').hide(); } // Latitude if (dcp_vars.show_latitude) { $('.dcp-latitude-header, .dcp-latitude-cell').show(); } else { $('.dcp-latitude-header, .dcp-latitude-cell').hide(); } // Longitude if (dcp_vars.show_longitude) { $('.dcp-longitude-header, .dcp-longitude-cell').show(); } else { $('.dcp-longitude-header, .dcp-longitude-cell').hide(); } // Altitude if (dcp_vars.show_altitude) { $('.dcp-altitude-header, .dcp-altitude-cell').show(); } else { $('.dcp-altitude-header, .dcp-altitude-cell').hide(); } // Country if (dcp_vars.show_country) { $('.dcp-country-header, .dcp-country-cell').show(); } else { $('.dcp-country-header, .dcp-country-cell').hide(); } } else { $('#dcp-from-table-container, #dcp-to-table-container').hide(); } // Show/hide entire sections if both map and table are hidden if (!getSettingValue('show_from_map') && !getSettingValue('show_location_table')) { $('#dcp-from-location-container').hide(); } else { $('#dcp-from-location-container').show(); } if (!getSettingValue('show_to_map') && !getSettingValue('show_location_table')) { $('#dcp-to-location-container').hide(); } else { $('#dcp-to-location-container').show(); } } else { alert('Error: ' + response.data); } }, error: function(xhr, status, error) { console.error('AJAX error:', status, error); alert('Calculation failed. Please try again.'); }, complete: function() { if (showLoading) { $button.removeClass('loading').prop('disabled', false); } } }); } // Initialize input maps function initInputMap(mapId, inputId) { console.log('Initializing input map:', mapId); // Check if container exists const $container = $('#' + mapId); if ($container.length === 0) { console.error('Input map container not found:', mapId); return; } try { // Destroy existing map if any destroyMap(mapId); // Create map with configured zoom const map = L.map(mapId).setView([40.7128, -74.0060], dcp_vars.input_map_zoom); // Store map instance mapInstances[mapId] = map; // Add tiles L.tileLayer(dcp_vars.osm_tiles, { attribution: '© OpenStreetMap contributors' }).addTo(map); // Add zoom control L.control.zoom({ position: 'topright' }).addTo(map); let marker = null; // Add click event map.on('click', function(e) { const lat = e.latlng.lat; const lng = e.latlng.lng; // Remove existing marker if (marker) { map.removeLayer(marker); } // Add new marker marker = L.marker([lat, lng]).addTo(map); // Update input field $('#' + inputId).val(lat + ', ' + lng); }); // Function to set marker for location function setMarkerForLocation(location) { fetch('https://nominatim.openstreetmap.org/search?format=json&q=' + encodeURIComponent(location)) .then(response => response.json()) .then(data => { if (data && data.length > 0) { const lat = parseFloat(data[0].lat); const lon = parseFloat(data[0].lon); console.log('Found coordinates:', lat, lon); map.setView([lat, lon], Math.max(dcp_vars.input_map_zoom, 10)); marker = L.marker([lat, lon]).addTo(map); } else { console.warn('No results found for:', location); } }) .catch(error => { console.error('Error geocoding location:', location, error); }); } // Set marker if input has value const inputValue = $('#' + inputId).val(); if (inputValue) { console.log('Setting marker for input value:', inputValue); setMarkerForLocation(inputValue); } console.log('Input map initialized successfully:', mapId); } catch (error) { console.error('Error initializing input map:', mapId, error); } } // Initialize main route map function initMainMap(from, to) { console.log('Initializing main route map'); // Check if container exists const $container = $('#dcp-map'); if ($container.length === 0) { console.error('Main map container not found'); return; } try { // Destroy existing map if any destroyMap('dcp-map'); // Clear container $container.empty(); // Create map with configured zoom const map = L.map('dcp-map').setView([from.lat, from.lon], dcp_vars.route_map_zoom); // Store map instance mapInstances['dcp-map'] = map; // Add tiles L.tileLayer(dcp_vars.osm_tiles, { attribution: '© OpenStreetMap contributors' }).addTo(map); // Add zoom control L.control.zoom({ position: 'topright' }).addTo(map); // Add markers const startMarker = L.marker([from.lat, from.lon]) .addTo(map) .bindPopup('From: ' + from.display_name); const endMarker = L.marker([to.lat, to.lon]) .addTo(map) .bindPopup('To: ' + to.display_name); // Draw line L.polyline([ [from.lat, from.lon], [to.lat, to.lon] ], { color: '#007bff', weight: 4, opacity: 0.7, dashArray: '10, 10' }).addTo(map); // Fit bounds const group = new L.featureGroup([startMarker, endMarker]); map.fitBounds(group.getBounds().pad(0.1)); console.log('Main route map initialized successfully'); } catch (error) { console.error('Error initializing main route map:', error); } } // Initialize location map function initLocationMap(mapId, location, title) { console.log('Initializing location map:', mapId); // Check if container exists const $container = $('#' + mapId); if ($container.length === 0) { console.error('Location map container not found:', mapId); return; } try { // Destroy existing map if any destroyMap(mapId); // Clear container $container.empty(); // Create map with configured zoom const map = L.map(mapId).setView([location.lat, location.lon], dcp_vars.location_map_zoom); // Store map instance mapInstances[mapId] = map; // Add tiles L.tileLayer(dcp_vars.osm_tiles, { attribution: '© OpenStreetMap contributors' }).addTo(map); // Add zoom control L.control.zoom({ position: 'topright' }).addTo(map); // Add marker L.marker([location.lat, location.lon]) .addTo(map) .bindPopup(title + ': ' + location.display_name); // Add circle L.circle([location.lat, location.lon], { color: '#007bff', fillColor: '#007bff', fillOpacity: 0.1, radius: 1000 }).addTo(map); // Force map to refresh after a short delay setTimeout(function() { if (mapInstances[mapId]) { mapInstances[mapId].invalidateSize(); } }, 100); console.log('Location map initialized successfully:', mapId); } catch (error) { console.error('Error initializing location map:', mapId, error); } } // Initialize maps and set default values function initializeWithDefaults() { console.log('Initializing with default values'); // Set default values if available if (dcp_vars.default_from) { console.log('Setting default from value:', dcp_vars.default_from); $('#dcp-from').val(dcp_vars.default_from); } if (dcp_vars.default_to) { console.log('Setting default to value:', dcp_vars.default_to); $('#dcp-to').val(dcp_vars.default_to); } // Set shortcode attributes if available if (typeof dcp_shortcode_atts !== 'undefined') { if (dcp_shortcode_atts.from) { console.log('Setting shortcode from value:', dcp_shortcode_atts.from); $('#dcp-from').val(dcp_shortcode_atts.from); } if (dcp_shortcode_atts.to) { console.log('Setting shortcode to value:', dcp_shortcode_atts.to); $('#dcp-to').val(dcp_shortcode_atts.to); } } // Initialize input maps initInputMap('dcp-from-map', 'dcp-from'); initInputMap('dcp-to-map', 'dcp-to'); // Calculate with default values if both are set if (dcp_vars.default_from && dcp_vars.default_to) { console.log('Both default values set, will calculate automatically'); setTimeout(function() { console.log('Calculating with default values'); calculateDistance(dcp_vars.default_from, dcp_vars.default_to, false); }, 3000); // Increased delay to ensure maps are initialized and markers are set } // Calculate with shortcode attributes if both are set if (typeof dcp_shortcode_atts !== 'undefined' && dcp_shortcode_atts.from && dcp_shortcode_atts.to) { console.log('Both shortcode attributes set, will calculate automatically'); setTimeout(function() { console.log('Calculating with shortcode attributes'); calculateDistance(dcp_shortcode_atts.from, dcp_shortcode_atts.to, false); }, 3000); } } // Initialize when page loads initializeWithDefaults(); // Calculate button click $('#dcp-calculate').on('click', function() { console.log('Calculate button clicked'); const from = $('#dcp-from').val(); const to = $('#dcp-to').val(); calculateDistance(from, to, true); }); }); https://indiantouristplace.com/post-sitemap.xml 2026-02-23T08:07:34+00:00 https://indiantouristplace.com/page-sitemap.xml 2026-02-23T07:45:36+00:00 https://indiantouristplace.com/category-sitemap.xml 2026-02-23T08:07:34+00:00