Добавление карты и маркера Leavletjs в проект LaravelPhp

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Добавление карты и маркера Leavletjs в проект Laravel

Сообщение Anonymous »

Появляются маркеры, но сама карта пустая, когда показывают маркеры, но на страницах без представленного списка и маркеров карта отображает < /p>



document.addEventListener("DOMContentLoaded", function () {
// Initialize the map with Brampton coordinates and a zoom level
var map = L.map('map').setView([43.7315, -79.7624], 13);

// Add a tile layer using OpenStreetMap
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap'
}).addTo(map);

// Get housing locations from the backend as JSON
var housingLocations = @json($housingLocations);

// Create a feature group for markers
var markers = L.featureGroup();

// Loop through each housing location and add a marker if valid coordinates exist
housingLocations.forEach(function(location) {
console.log("Location:", location);
if (location.lat && location.lon) {
console.log("Adding marker at:", location.lat, location.lon);
var marker = L.marker([location.lat, location.lon]);
var popupContent = '' + location.name + '
' +
location.address + '
' +
location.city + ', ' + location.province + ' ' + location.postal_code;
marker.bindPopup(popupContent);
markers.addLayer(marker);
} else {
console.log("Invalid coordinates:", location.lat, location.lon);
}
});

// Add all markers to the map
map.addLayer(markers);
if (housingLocations.length > 0 && markers.getLayers().length > 0) {
map.fitBounds(markers.getBounds());
}

// Invalidate map size after a short delay to ensure proper rendering
setTimeout(function() {
map.invalidateSize();
}, 500);
});

< /code>
/ Fetch housing locations for the map (same query as HousingMapController)
$housingLocations = DB::table('housing_metas')
->join('housings', 'housing_metas.HousingID', '=', 'housings.ID')
->select(
'housings.Name as name',
'housings.Type as type',
'housings.Status as status',
'housing_metas.Address as address',
'housing_metas.City as city',
'housing_metas.Province as province',
'housing_metas.PostalCode as postal_code',
'housing_metas.Lon as lon',
'housing_metas.Lat as lat'
)
->whereIn('housings.ID', $housingIDs)
->where('housing_metas.City', '=', 'Brampton')
->whereIn('housings.Type', ['p', 'b'])
->whereNotNull('housing_metas.Lon')
->where('housing_metas.Lon', '!=', 0)
->get();

return view('frontend.residence_type', [
'page_title' => 'Types of Residence',
'housings' => $housings,
'category' => $category, // Pass category to view
'housingLocations' => $housingLocations
]);
}
}
< /code>
Below is a short summary of what my code has accomplished so far:
• Leaflet Assets:
– The Leaflet CSS and JS libraries are included via CDN to enable map rendering and functionality.
• Map Container & Styling:
– A div with the id "map" is defined with a fixed height and full width to display the map.
• Map Initialization:
– On DOMContentLoaded, a Leaflet map is initialized with a central coordinate (Brampton) and a specified zoom level.
• Tile Layer Setup:
– The map uses OpenStreetMap tiles, loaded via HTTPS, with proper attribution.
• Markers Data:
– Housing location data is passed from the backend (via the $housingLocations JSON object) to JavaScript.
• Markers Creation:
– A feature group is created, and for each housing location that has valid latitude and longitude, a marker is added with a popup containing the name, address, city, province, and postal code.
• Map View Adjustment:
– Once the markers are added, the map’s view is adjusted to fit all markers (using fitBounds) and the map size is validated with invalidateSize after a short delay.
This setup allows to dynamically display housing markers on a Leaflet map within your Laravel application.

Подробнее здесь: https://stackoverflow.com/questions/794 ... el-project
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»