Появляются маркеры, но сама карта пустая, когда показывают маркеры, но на страницах без представленного списка и маркеров карта отображает < /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
Добавление карты и маркера Leavletjs в проект Laravel ⇐ Php
Кемеровские программисты php общаются здесь
-
Anonymous
1739274126
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: '© [url=http://www.openstreetmap.org/copyright]OpenStreetMap[/url]'
}).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 = '[b]' + location.name + '[/b]
' +
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.
Подробнее здесь: [url]https://stackoverflow.com/questions/79429847/adding-leafletjs-map-and-marker-to-a-laravel-project[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия