I am working on google map. Onclick image, google map display on bootstrap modal, to display route path using latlng. All functionality is working properly but
The map start position marker, I want to center the marker position when the map is load, just now it's as per image. The start point it's in the top left corner. I have checked so many example, but all are not working in my code.
Also i tried using resize, trigger function.
google.maps.event.trigger(map, 'resize');
map = new google.maps.Map(document.getElementById("map_canvas"), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
HTML
Click
Modal and Script
<div id="mapModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="gridModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<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" id="gridModalLabel">Map Display</h4>
</div>
<div class="modal-body">
<div class="container-fluid bd-example-row">
<div class="row">
<div id="map_polyline" style="width: 100%; height: 655px;"></div>
<script type="text/javascript">
function initialize() {
var mapProp = new google.maps.Map(document.getElementById('map_polyline'), {
zoom: 15,
maxZoom: 30,
minZoom: 1,
streetViewControl: false,
center: new google.maps.LatLng(23.01780,72.53076),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myTrip=new Array();
myTrip.push(new google.maps.LatLng(23.01780,72.53076));
myTrip.push(new google.maps.LatLng(23.01846,72.52987));
myTrip.push(new google.maps.LatLng(23.01909,72.53054));
myTrip.push(new google.maps.LatLng(23.01954,72.52991));
myTrip.push(new google.maps.LatLng(23.02060,72.53064));
myTrip.push(new google.maps.LatLng(23.02125,72.53006));
myTrip.push(new google.maps.LatLng(23.02237,72.53076));
myTrip.push(new google.maps.LatLng(23.02306,72.52988));
myTrip.push(new google.maps.LatLng(23.02438,72.53021));
myTrip.push(new google.maps.LatLng(23.02467,72.52899));
myTrip.push(new google.maps.LatLng(23.02486,72.52769));
myTrip.push(new google.maps.LatLng(23.02555,72.52695));
myTrip.push(new google.maps.LatLng(23.02616,72.52656));
myTrip.push(new google.maps.LatLng(23.02704,72.52641));
myTrip.push(new google.maps.LatLng(23.02868,72.52664));
myTrip.push(new google.maps.LatLng(23.03068,72.52700));
myTrip.push(new google.maps.LatLng(23.03173,72.52555));
var flightPath=new google.maps.Polyline({
path:myTrip,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2
});
flightPath.setMap(mapProp);
google.maps.event.trigger(mapProp, 'resize');
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
try this
$('#myMapModal').on('show.bs.modal', function() {
resizeMap();
})
function resizeMap() {
if(typeof map =="undefined") return;
setTimeout( function(){resizingMap();} , 400);
}
function resizingMap() {
if(typeof map =="undefined") return;
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
}
Related
i have list of lat long stored in db $order->customers->location_url and (location_url = 31.5952599,74.3526989 have data in this form) using foreach loop i am trying to print all markers on map in model but when i click to button it shows blank screen check screen shot even doesnot start map
here is my code that i am using to show map
html
<button class="btn-sm" type="button" data-toggle="modal" onclick ='initialize();' data-target="#map-modal-points">Show All Points</button>
model
<div class="modal fade" id="map-modal-points" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">All Shops</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="map_canvas" style="height: 400px"></div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary">Close</button>
</div>
</div>
</div>
</div>
java script
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
function initialize() {
var locations = [
#foreach ($orders as $order)
[ {{ $order->customers->location_url }} ]
#endforeach
];
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
</script>
i am using this code to print map Laravel and google maps : foreach latitude/longitude show marker or map
is there any other way i can print all markers ? or what mistake i am making in it?
I'm writing an MVC project that includes the possibility to add points in a Google map. So far I can add points to db by hardcoding latitude and longitude values, but I want to let the user select the position on the map and send them back to the controller from the Razor view.
I have already written part of the view and I'm able to open a modal popup with the map and a hardcoded location.
What I want to do is:
1. let the user insert an address in a textbox
2. open the modal popup and have the map centered with a marker near the address
3. save back the position in two fields of the view in order to send them back to the controller.
I have been using the code provided by Google Developers at:
https://developers.google.com/maps/documentation/javascript/examples/place-details
and have come to the following code:
All the code is in the Razor View:
<form>
<fieldset>
<legend>Ubicazione: </legend>
<div class="form-group">
#Html.LabelFor(model => model.Indirizzo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<button type="button" class="btn btn-default" style="float:left"
data-toggle="modal" data-target="#findInModal" data-backdrop="static"
data-keyboard="true" data-address='pippo'>
Trova posizione
</button>
#Html.EditorFor(model => model.Indirizzo, new { htmlAttributes = new { #class = "form-control" }, #id="addr" })
#Html.ValidationMessageFor(model => model.Indirizzo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Latitudine, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.EditorFor(model => model.Latitudine, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.DisplayFor(model => model.Latitudine, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(model => model.Latitudine)
#Html.ValidationMessageFor(model => model.Latitudine, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Longitudine, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.EditorFor(model => model.Longitudine, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.DisplayFor(model => model.Longitudine, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(model => model.Longitudine)
#Html.ValidationMessageFor(model => model.Longitudine, "", new { #class = "text-danger" })
</div>
</div>
</fieldset>
</form>
I would like the value of the data-address='pippo' to be the address in the "#Html.EditorFor(model => model.Indirizzo …."
Here is the modal popup content that opens the map and centers it to a hardcoded position:
<!-- Find Location In Modal -->
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="modal fade" id="findInModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" style="height: 0px;"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Chiudi">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="gMap" style="height:400px;width:100%;"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=APIKEY&language=it®ion=IT&libraries=places&callback=gMap" async defer></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
let myCenter;
let mapProp;
let map;
let service;
function gMap() {
myCenter = new google.maps.LatLng(41.893140, 12.483330);
mapProp = { center: myCenter, zoom: 15, scrollwheel: true, draggable: true, mapTypeId: google.maps.MapTypeId.HYBRID };
map = new google.maps.Map(document.getElementById("gMap"), mapProp);
let request = {
query: 'Musei Capitolini',
fields: ['name', 'geometry'],
};
service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(request, function (results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (let i = 0; i < results.length; i++) {
createMarker(results[i]);
}
map.setCenter(results[0].geometry.location);
}
});
}
function createMarker(place) {
let marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: "/Content/icons/01.png"
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(place.name + place.geometry.location);
infowindow.open(map, this);
});
}
</script>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Chiudi</button>
<button type="button" class="btn btn-primary">Salva</button>
</div>
</div>
</div>
</div>
}
and here is the script that open the popup:
<script>
$('#findInModal').on('show.bs.modal', function (event) {
let button = $(event.relatedTarget) // Button that triggered the modal
let AddressToFind = button.data('address') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
let modal = $(this)
modal.find('.modal-title').text('Find near: ' + AddressToFind)
})
</script>
At the moment I have not implemented how to return the place.geometry.location values to the parent view, but they are suppose to update the model => model.Latitudine and model => model.Longitudine values that will be returned to the controller to update the db.
Thank in advance for any help.
No help from devs, but going deep into the Google Developers documentation and testing it at JSFiddle, I finally came out with the following solution:
#model GoogleMapTest.Models.MapPoint
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>MapPoint</legend>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
#Html.DisplayFor(model => model.Address)
#Html.HiddenFor(model => model.Address, new { id = "Address" })
#Html.ValidationMessageFor(model => model.Address)
</div>
<button type="button" class="btn btn-default" style="float: left"
data-toggle="modal" data-target="#findInModal" data-backdrop="static"
data-keyboard="true">
Find Position
</button>
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Latitude)
</div>
<div class="editor-field">
#Html.DisplayFor(model => model.Latitude)
#Html.HiddenFor(model => model.Latitude, new { id = "Latitude" })
#Html.ValidationMessageFor(model => model.Latitude)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Longitude)
</div>
<div class="editor-field">
#Html.DisplayFor(model => model.Longitude)
#Html.HiddenFor(model => model.Longitude, new { id = "Longitude" })
#Html.ValidationMessageFor(model => model.Longitude)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<!-- Find Location In Modal -->
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="modal fade" id="findInModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" style="height: 0px;">Set Point in Map</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<input id="pac-input" class="controls" type="text" placeholder="Find...">
<div id="gMap" style="height:400px;width:100%;"></div>
<script src="https://maps.google.com/maps/api/js?sensor=false&key=AIzaSyDMD8_QumYpomzDTcHW-myppqsyCZRsnB8"
// APIkey end with call to libraries "&libraries=places&callback=initAutocomplete"
async defer></script>
<script>
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('gMap'), {
center: { lat: 41.893321, lng: 12.482929 },
zoom: 13,
mapTypeId: 'hybrid',
scrollwheel: true,
zoomControl: false,
scaleControl: true,
streetViewControl: false,
fullscreenControl: false,
mapTypeControl: false
});
// 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());
});
var markers = [];
// 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;
}
// 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) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
// create infowindow: just while debugging not needed in View
var infowindow = new google.maps.InfoWindow();
// create geocoder for address
var geocoder = new google.maps.Geocoder();
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
//icon: "/Content/icons/01.png",
title: place.name,
position: place.geometry.location,
draggable: true
}));
// Add listeners to marker:
// click: opens infowindow
markers[0].addListener('click', function () {
infowindow.open(map, markers[0]);
infowindow.setContent(place.name + ': ' + place.geometry.location);
infowindow.open(map, this);
// Add listeners to map
google.maps.event.addListener(markers[0], 'dragend', function (evt) {
infowindow.setContent('Lat: ' + evt.latLng.lat() + ' Lng: ' + evt.latLng.lng());
infowindow.open(map, this);
map.setCenter(markers[0].getPosition());
markers[0].setMap(map);
map.setTilt(0);
map.setZoom(20);
// update return values
// gLat, gLong, gAddr are global variables
gLat = evt.latLng.lat();
gLong = evt.latLng.lng();
// get address
var latlng = { lat: parseFloat(gLat), lng: parseFloat(gLong) };
geocoder.geocode({ 'location': latlng }, function (results, status) {
if (status === 'OK') {
if (results[0]) { gAddr = results[0].formatted_address } else {
gAddr = 'NotFound';
}
}
});
});
});
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
</script>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Chiudi</button>
<button type="button" class="btn btn-primary" onclick="updFields(gLat, gLong, gAddr)">Salva</button>
</div>
</div>
</div>
</div>
}
<script>
$('#findInModal').on('show.bs.modal', function () {
})
function updFields(lat,lng, addr) {
//alert('Lat: ' + lat + '\nLng: ' + lng + '\nAddr: ' + addr);
//document.getElementById("Address").value = addr;
//document.getElementById("Latitude").value = lat;
//document.getElementById("Longitude").value = lng;
$('#Address').val(addr);
$('#Latitude').val(lat);
$('#Longitude').val(lng);
}
</script>
infowindow and alerts are just in while developing, but are not part of the final solution.
Basically I implemented a Google Maps Search Box with the Autocomplete and Place service, and a Geocoder to retrieve the address from the coordinators.To this I added a function that updates my hidden fields.The code of the view is much more complex because it contains other fields not relevant to the position in the map and makes it possible to manually modify the fields, but basically this is the backbone of the code.
I would have like to post images, it seem that my APIkey has overgone quota.
I'm trying to put two buttons underneath my google maps canvas(One of which is a dropdown button). Without the buttons markup, the Google Maps loads fine. When I add the buttons code, the map disappears. The map element and the buttons are all within the same container and columns, but on different rows.
<div class="container-fluid pushdown">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8"><div class="map" id="map"></div></div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<div id="controls">
<button class="btn btn-default btn-lg dropdown-toggle location"type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Select<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><input type="checkbox" class="Check" name="traders[]" value="1"/><label class="CheckText">Trader1</label></li>
<li><input type="checkbox" class="traderCheck" name="traders[]" /><label class="traderCheckText">Trader2</label></li>
</ul>
<button onclick="location.href = 'search.html';" type="button" class="btn btn-default btn-lg" id="searchButton">Search <span class="glyphicon glyphicon-search"></span></button>
</div>
</div>
<div class="col-md-2"></div>
</div>
</div>
And the JS:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 16,
disableDefaultUI: true
});
var marker = new google.maps.Marker({
position: {lat: -34.397, lng: 150.644},
draggable:true
});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map.setCenter(pos);
marker.setPosition(pos);
marker.setMap(map);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
The map element CSS:
.map {
width: 100%;
height: 500px;
background-color: blue;
}
Also, I tried it with just the 3 columns on the second row(without the button elements) and the map disappeared . This means my problem is with Bootstrap.
Try this way .
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 16,
disableDefaultUI: true
});
var marker = new google.maps.Marker({
position: {lat: -34.397, lng: 150.644},
draggable:true
});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map.setCenter(pos);
marker.setPosition(pos);
marker.setMap(map);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCrwOEvG-QIFrYPBCwRVTvXvSuzcnz38Xs&signed_in=true&callback=initMap"
async defer>
</script>
.map{
width: 100%;
height: 500px;
background-color: blue;
}
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container-fluid pushdown">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8"><div class="map" id="map"></div></div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<div id="controls">
<button class="btn btn-default btn-lg dropdown-toggle location"type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Select<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>
<input type="checkbox" class="Check" name="traders[]" value="1"/>
<label class="CheckText">Trader1</label></li>
<li>
<input type="checkbox" class="traderCheck" name="traders[]" />
<label class="traderCheckText">Trader2</label></li>
</ul>
<button onclick="location.href = 'search.html';" type="button" class="btn btn-default btn-lg" id="searchButton">Search <span class="glyphicon glyphicon-search"></span></button>
</div>
</div>
<div class="col-md-2"></div>
I need to load google map .js api in bootstrap 3 modal box after click in link and open modalbox using google map initialize method like this :
html:
<a data-toggle="modal" href="#myModal" class="btn btn-primary">Launch modal</a>
<div class="modal" id="myModal">
<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">Location:
<input type="text" id="us2-address" style="width: 200px" />Radius:
<input type="text" id="us2-radius" />
<div id="us2" style="height: 400px;"></div>Lat.:
<input type="text" id="us2-lat" />Long.:
<input type="text" id="us2-lon" />
</div>
<div class="modal-footer"> Close
Save changes
</div>
</div>
</div>
</div>
JS:
var stillPresent = false;
function initialize() {
if (stillPresent == false) {
$('#us2').locationpicker({
location : {
latitude : 46.15242437752303,
longitude : 2.7470703125
},
radius : 300,
inputBinding : {
latitudeInput : $('#us2-lat'),
longitudeInput : $('#us2-lon'),
radiusInput : $('#us2-radius'),
locationNameInput : $('#us2-address')
}
});
stillPresent = true;
}
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://maps.google.com/maps/api/js?sensor=false&libraries=places&callback=initialize';
document.body.appendChild(script);
}
$('#myModal').on('shown.bs.modal', function(e) {
loadScript();
});
But in action this not work and not show map for me.
how do fix this problem?!
DEMO FIDDLE
The problem in your demo is the initialize() function is scoped within the onload handler. This can be seen in error thrown in browser console.
Change the scope so that the function is global within window namespace and code works fine.
I suspect in your production code you have scoped the function inside a jQuery ready handler.
I also suggest you only load the google maps script once if you plan on using modal more than once
DEMO
I need to load google map link(remote) after open modal box.
HTML:
<a data-toggle="modal" href="#myModal" class="btn btn-primary">Launch modal</a>
<div class="modal" id="myModal">
<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">Location:
<input type="text" id="us2-address" style="width: 200px" />Radius:
<input type="text" id="us2-radius" />
<div id="us2" style="height: 400px;"></div>Lat.:
<input type="text" id="us2-lat" />Long.:
<input type="text" id="us2-lon" />
</div>
<div class="modal-footer"> Close
Save changes
</div>
</div>
</div>
</div>
JS:
var stillPresent = false;
$('#myModal').on('shown.bs.modal', function (e) {
if(stillPresent == false){
$('#us2').locationpicker({
location: {
latitude: 46.15242437752303,
longitude: 2.7470703125
},
radius: 300,
inputBinding: {
latitudeInput: $('#us2-lat'),
longitudeInput: $('#us2-lon'),
radiusInput: $('#us2-radius'),
locationNameInput: $('#us2-address')
}
});
stillPresent = true;
}
})
google map link :http://maps.google.com/maps/api/js?sensor=false&libraries=places
DEMO : http://jsfiddle.net/Lzv7w/9/
if I add google map link into external resources jsfiddle worked. but I need to load google map link after open modal.
How to load this ?
Google has a nice tutorial herethat may help you. And the code below should fix your problem. Note that it may not work jsfiddle, but it should work on your real page.
var stillPresent = false;
function initialize() {
if (stillPresent == false) {
$('#us2').locationpicker({
location : {
latitude : 46.15242437752303,
longitude : 2.7470703125
},
radius : 300,
inputBinding : {
latitudeInput : $('#us2-lat'),
longitudeInput : $('#us2-lon'),
radiusInput : $('#us2-radius'),
locationNameInput : $('#us2-address')
}
});
stillPresent = true;
}
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://maps.google.com/maps/api/js?sensor=false&libraries=places&callback=initialize';
document.body.appendChild(script);
}
$('#myModal').on('shown.bs.modal', function(e) {
loadScript();
});
Also, here is a link to a similar question.