bootstrap 4 modal problem with leaflet map - javascript

I have problem with leaflet map when I use it in bootstrap 4 modal.
Map do not render correctly, and I don't know how to fix it.
this is my map script:
var url = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png';
var attr = '© OpenStreetMap contributors',
osm = L.tileLayer(url, {
maxZoom: 18,
attribution: attr
});
var map = L.map('mapId').setView([35.6892, 51.3890], 10).addLayer(osm);
map.on('click', onMapClick);
var markers = [];
function onMapClick(e) {
var geojsonFeature = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [e.latlng.lat, e.latlng.lng]
}
}
if (markers.length > 0) {
map.removeLayer(markers.pop());
}
var marker;
document.getElementById('latitude').value = e.latlng.lat;
document.getElementById('longitude').value = e.latlng.lng;
L.geoJson(geojsonFeature, {
pointToLayer: function (feature, latlng) {
marker = L.marker(e.latlng, {
riseOnHover: true,
draggable: true,
});
markers.push(marker);
return marker;
}
}).addTo(map);
}
I am looking for a solution to fix it::
This is my bootstrap modal code:
<div class="modal fade" id="mapModal" tabindex="-1" role="dialog" aria-labelledby="mapModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="mapModalLabel">انتخاب موقعیت مکانی ملک از روی نقشه:</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="mapId"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger btn-sm">ثبت</button>
</div>
</div>
</div>
</div>

i found it:
<script>
$('#mapModal').on('shown.bs.modal', function(){
setTimeout(function() {
map.invalidateSize();
}, 10);
});

Related

Bootstrap modal not showing when click on pie chart slice

<script>
$(document).ready(function(){
//get the pie chart canvas
var cData = JSON.parse(`<?php echo $chart_data; ?>`);
var data = {
// labels: cData.label,
datasets: [{
label: "Users Count",
data: cData.data,
backgroundColor: [
"#FF0000",
"#FFFF00",
"#008000",
],
borderColor: [
"#FF0000",
"#FFFF00",
"#008000",
],
borderWidth: [1, 1, 1]
}]
};
var options = {
responsive: true,
title: {
display: true,
position: "top",
text: "All Subject Progress",
fontSize: 18,
fontColor: "#111"
},
legend: {
display: true,
position: "bottom"
// labels: {
// fontColor: "#333",
// fontSize: 16
// }
}
};
var canvas = document.getElementById("pie-chart");
var ctx = canvas.getContext("2d");
var myNewChart = new Chart(ctx, {
type: 'pie',
data: data
});
canvas.onclick = function(evt) {
var activePoints = myNewChart.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
var value = chartData.datasets[0].data[idx];
var url = "http://example.com/?label=" + label + "&value=" + value;
//console.log(url);
//alert(url);
$("#myChartmodal").modal("show");
}
};
});
</script>
<div id="myChartmodal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
In this code I am creating pie-chart where it working perfectly. Now, I want to show bootstrap modal when I canvas.onclick. Here, What happen when I click on canvas.onclick only alert message are showing right now but $("#myChartmodal").modal("show"); is not working I don't know why. So, How can I open bootstrap modal after click on every slice of pie-chart? Please help me.
Thank You
Your show modal code should work as shown below, just need to include the bootstrap libraries as shown below
$(function(){
$('show').on('click', function(){
$('#myChartmodal').modal('show');
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<div id="myChartmodal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<input type="button" value="Show Popup" id="show" data-toggle="modal" data-target="#myChartmodal">

How do I have each marker when clicked on show data for its specific marker in the modal- Gmaps4Rails

I wanted to have a modal pop up whenever I click on a marker in google maps. I was able to accomplish this with the following script code in javascript (in my view):
handler = Gmaps.build('Google', {
// builders: {
// Marker: InfoBoxBuilder
// },
markers:
{clusterer: {
gridSize: 60,
maxZoom: 20,
styles: [ {
textSize: 10,
textColor: '#ff0000',
url: 'assets/creative/m1.png',
height: 60,
width: 60 }
, {
textSize: 14,
textColor: '#ffff00',
url:'assets/creative/m2.png',
height: 60,
width: 60 }
, {
textSize: 18,
textColor: '#0000ff',
url: 'assets/creative/m3.png',
width: 60,
height: 60}
]}}
});
handler.buildMap({ provider: {}, internal: {id: 'map'}}, function() {
var i, len, marker, results;
markers = handler.addMarkers(<%=raw #hash.to_json %>);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
results = [];
for (i = 0, len = markers.length; i < len; i++) {
marker = markers[i];
google.maps.event.addListener(marker.getServiceObject(), 'click', function() {
$('#myModal').modal('show')
return true;
});
results.push(true);
}
return results;
});
In my view:
<div id="map" style='width: 100%; height: 900px;'>
</div>
<% #maps.each do |map| %>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel"><%= map.number %></h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<% end %>
Here is my controller:
class MapsController < ApplicationController
def index
#maps = Map.all
#hash = Gmaps4rails.build_markers(#maps) do |map, marker|
marker.lat map.latitude
marker.lng map.longitude
marker.title map.number
marker.json({:id => map.id })
# marker.infowindow render_to_string(:partial => "/maps/info", :locals => { :object => map})
end
end
def import
Map.import(params[:file])
redirect_to authors_posts_path, notice: "Locations Imported!"
end
def show
end
end
The problem I am having is whenever I click on a marker the modal only shows the map.number for the first object for every marker. I want to, when I click on a marker, for the data that is shown in the modal be only for the marker that is clicked on.
Modal Image with map.number
I would say you have two way to approach the issue.
If you keep one modal per marker, have different ids for each modal.
<div class="modal fade" id="myModal-<%= map.id %>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
and in the js:
handler.buildMap({ provider: {}, internal: {id: 'map'}}, function() {
var i, len, results;
markers = handler.addMarkers(<%=raw #hash.to_json %>);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
$.each(markers, function(index, marker) {
google.maps.event.addListener(marker.getServiceObject(), 'click', function() {
$('#myModal-' + marker.id).modal('show');
});
});
});
Or have one modal for all and populate it on the fly:
handler.buildMap({ provider: {}, internal: {id: 'map'}}, function() {
var i, len, results;
markers = handler.addMarkers(<%=raw #hash.to_json %>);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
$.each(markers, function(index, marker) {
google.maps.event.addListener(marker.getServiceObject(), 'click', function() {
$('#myModal #myModalLabel').text(marker.title);
$('#myModal').modal('show');
});
});
});

Google Maps API multiple times on this page - Modal Bootstrap Return Json Success

The problem is when I open modal bootstrap which carries Google Maps.
Modal Bootstrap - _Edit.cshtml
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Editar</h4>
</div>
#using (Ajax.BeginForm("Edit", "Account", new AjaxOptions { HttpMethod = "POST", OnSuccess = "onModalSuccess" }, new { #id = "ModalformId", #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-xs-6">
#Html.LabelFor(m => m.GoogleMaps_Link)
#Html.TextBoxFor(m => m.GoogleMaps_Link, new { #id = "pac-input", #class = "controls", #readonly = true })
<br />
<div id="map-canvas" class="Help_GoogleMaps" style="width:865px;height:380px;" title="Edit"></div>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Save" />
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
#*Success Message Modal*#
<div id="ModalMsgBoxId" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">
<strong id="ModalTitleId" style="margin-left: 6px; font-size: 16px;"></strong>
</h4>
</div>
<div class="modal-body">
<p>
<div id="ModalContentId" style="margin-left: 6px; font-size: 16px;"></div>
</p>
</div>
<div class="modal-footer">
<button id="normalOkId" type="button" class="btn btn-success" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
}
// Google Maps Search
<script>
$(document).on("shown.bs.modal", function () {
if (window.google && window.google.maps) {
initAutocomplete();
return;
}
$script = $("<script>",
{
'type': 'text/javascript',
'src': 'https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&libraries=places&callback=initAutocomplete'
});
$script.appendTo($("head"));
});
function initAutocomplete() {
var LatLong = #Html.Raw(JsonConvert.SerializeObject(Model.Geo));
var LatLongSplit = LatLong.split(" ");
var lat = LatLongSplit[0];
var long = LatLongSplit[1];
//var Lat = (-23.5326148);
//var Long = (-46.803688);
var Endereco = #Html.Raw(JsonConvert.SerializeObject(Model.GoogleMaps_Link));
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(lat, long),
zoom: 11,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var markerLatLong = new google.maps.Marker({
position: new google.maps.LatLng(lat, long),
map: map,
title: Endereco
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
});
//Clear Markers
var markers = [];
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
markerLatLong.setMap(null);
// Clear out the old markers.
markers.forEach(function (marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
// [END region_getplaces]
}
var onModalSuccess = function(result)
{
if (result.EnableError)
{
// Clear.
$('#ModalTitleId').html("");
$('#ModalContentId').html("");
// Setting.
$('#ModalTitleId').append(result.ErrorTitle);
$('#ModalContentId').append(result.ErrorMsg);
// Show Modal.
$('#ModalMsgBoxId').modal(
{
backdrop: 'static',
keyboard: false
});
}
else if (result.EnableSuccess)
{
// Clear.
$('#ModalTitleId').html("");
$('#ModalContentId').html("");
// Setting.
$('#ModalTitleId').append(result.SuccessTitle);
$('#ModalContentId').append(result.SuccessMsg);
// Show Modal.
$('#ModalMsgBoxId').modal(
{
backdrop: 'static',
keyboard: false
});
// Resetting form.
$('#ModalformId').get(0).reset();
}
}
</script>
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(EditModel model)
{
if (ModelState.IsValid)
{
return this.Json(new { EnableSuccess = true, SuccessTitle = "Success", SuccessMsg = "Success" });
}
retur PartialView (_Edit, model);
}
The problem is in partial view. Just show a warning!
With the code below:
<div id="ModalMsgBoxId" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">
<strong id="ModalTitleId" style="margin-left: 6px; font-size: 16px;"></strong>
</h4>
</div>
<div class="modal-body">
<p>
<div id="ModalContentId" style="margin-left: 6px; font-size: 16px;"></div>
</p>
</div>
<div class="modal-footer">
<button id="normalOkId" type="button" class="btn btn-success" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
Picture:
The problem is modal Success, does it make Google Maps fail. How can I fix?
Thank you guys.
I solved the problem in another way. Using Bootstrap Alert.
Link: Alerts - Bootstrap
Remove code:
<div id="ModalMsgBoxId" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">
<strong id="ModalTitleId" style="margin-left: 6px; font-size: 16px;"></strong>
</h4>
</div>
<div class="modal-body">
<p>
<div id="ModalContentId" style="margin-left: 6px; font-size: 16px;"></div>
</p>
</div>
<div class="modal-footer">
<button id="normalOkId" type="button" class="btn btn-success" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
New code:
<center><div id="result"></div></center>
javascript:
$("#result").html('<div class="alert alert-success"><button type="button" class="close">×</button>Successfully updated record!</div>');
Now it works! I took example link: here

Google map not showing on bootstrap modal

Im am planning to show a google map on a modal, but the map is not showing from the modal
This is my code:
<div style="margin-top:-7px;">
<button class="btn btn-default pull-right btn-mini " style="margin-right:5px;" data-toggle="modal" data-target="#myModal7"><i class="fa fa-globe"></i> Show Map</button>
</div>
<div class="modal inmodal fade" id="myModal7" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Address</h4>
</div>
<div class="modal-body">
<div class="panel mb25 mt5" style="width:500px; margin:0 auto; padding:10px;">
<div id="map" style="width: 500px; height: 500px;"></div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script type="text/javascript">
var address = 'Japan';
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16
});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
google.maps.event.trigger(map, 'resize');
map.setCenter(results[0].geometry.location);
}
});
</script>
I did a research for this problem, ang i got the common answer, it is google.maps.event.trigger(map, "resize"); the problem is where will i put it, please help me.
Thanks
google map has problem with "display:none" parent.
initialize your map after showing modal for first time.
add a class for button or link that show modal.
$('.modal-opener-btn').one('click', function(){
//putt your code here
});
NOTICE : use "one" and dont use "on"
NOTICE : also can use modal "shown" listener, if this solution doesn't work
$('#myModal7').on('shown', function(){
//putt your code here
});
Just change bottom script tag and contents to :
<script type="text/javascript">
function init(){
var address = 'Japan';
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16
});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
google.maps.event.trigger(map, 'resize');
map.setCenter(results[0].geometry.location);
}
});
}
$('#myModal7').on('shown.bs.modal', function(){
init();
});
</script>
regarding your research you can try to use that function
inside this
$(document).ready(function(){
$('#your_modal_id').on('shown.bs.modal',function(){
google.maps.event.trigger(map, "resize");
});
});
Had the same problem and this was the solution that made my day:
Make sure that you have jQuery on the initial page that called your modal page:

passing data to modal(bootstrap)

I have a multiple markers on google map and when i click them i need to open a modal window. The problem is every marker has a specific id and i need that id in each modal.
The modal html is:
<div class="modal fade" id="imageModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
The javascript code calling this function is :
function createMarker(pos, t, map) {
var marker = new google.maps.Marker({
position: pos,
map: map, // google.maps.Map
index: t
});
google.maps.event.addListener(marker, 'click', function() {
$('#imageModal').modal();
//alert("I am marker " + marker.index);
});
return marker;
}
So in imageModal i need to access the marker.index information which is dynamic. How can i do that? any ideas ?
Firstly I don't think index is a MarkerOption in Google Maps v3.
How I got this is, I used the title option in MarkerOption and it set to a dynamic string and then accessed it in the addListener event.
Here's how you can do it:
function createMarker(pos, t, map) {
var marker = new google.maps.Marker({
position: pos,
map: map, // google.maps.Map
title: t //where t must be a string
});
google.maps.event.addListener(marker, 'click', function() {
$('#imageModal').modal();
alert("I am marker " + this.getTitle() );
});
}
Hope this helps you!!

Categories