Google Maps Search Box with autocomplete in Modal - javascript

Is it possible to have the Google Maps search box with autocomplete in a modal?
Not the whole map, just the search box.
Something like this:

Hours later seems that I found out a way to do it :)
HTML:
<div class="modal fade" id="searchModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-md" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="md-form ml-0 mr-0">
<!-- Autocomplete location search input -->
<div class="form-group">
<label>Τοποθεσία:</label>
<input type="text" class="form-control" id="search_input" placeholder="Αναζήτηση διεύθυνσης..." />
<input type="hidden" id="loc_lat" />
<input type="hidden" id="loc_long" />
</div>
<!-- Display latitude and longitude -->
<div class="latlong-view">
<p style="text-align: center;">
<b>Latitude:</b>
<span id="latitude_view"></span>
<b>| Longitude:</b>
<span id="longitude_view"></span>
</p>
</div>
</div>
<div class="text-center mt-4">
<button class="btn btn-cyan waves-effect waves-light" onclick="goTo()" style=" font-size: 1.2rem;">
<i class="fa fa-search ml-1"></i>
</button>
</div>
</div>
</div>
</div>
Javascript:
/* Google Maps Search handler */
var searchInput = 'search_input';
$(document).ready(function() {
var autocomplete;
autocomplete = new google.maps.places.Autocomplete((document.getElementById(searchInput)), {
types: ['geocode'],
componentRestrictions: {
country: "GR"
}
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var near_place = autocomplete.getPlace();
document.getElementById('loc_lat').value = near_place.geometry.location.lat();
document.getElementById('loc_long').value = near_place.geometry.location.lng();
document.getElementById('latitude_view').innerHTML = near_place.geometry.location.lat();
document.getElementById('longitude_view').innerHTML = near_place.geometry.location.lng();
});
});
$(document).on('change', '#' + searchInput, function() {
document.getElementById('latitude_view').innerHTML = '';
document.getElementById('longitude_view').innerHTML = '';
});
/* Google Maps - Go to searched location */
function goTo() {
var lat = Number(document.getElementById("latitude_view").innerText);
var lon = Number(document.getElementById("longitude_view").innerText);
console.log(lat);
console.log(lon);
if (lat != 0 && lon != 0) {
map.setCenter({
lat: lat,
lng: lon
});
map.setZoom(18);
} else
alert("Μη αποδεκτές συντεταγμένες");
}
/* END of Google Maps Search handler */
Please note that you have to use the places library in order to make it work.
<script defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&callback=initMap"></script>

Related

How to optimise my partial view loading time? (C#, MVC, jQuery)

For this feature, I want the respective tour package details (partial view.cshtml) to load in the main view (view.cshtml) as I select the different options. The problem I am facing now is that, the partial view content loads way too slowly.
For example,
Tour A package detail: New Zealand Tour (16 Day)
Tour B pacakage detail: New Zealand Tour (14 Day)
if i click onto card A, it takes a long time for New Zealand Tour (16 Day) to appear
if i click onto card B, New Zealand Tour (16 Day) will still be there, only after a long time of waiting, then it will switch to New Zealand Tour (14 Day)
sorry i tried to attach the gif demo but it doesn't allow me to upload
here are my codes:
View.cshtml
#using StiWebsite.Models;
#using System.Security.Policy
#model dynamic
#{
ViewData["Title"] = "Experiential";
}
<div class="row addCss3" style="padding: 0 1rem" id="paddingRow">
<div class="col-sm-12 col-xs-12 col-md-12 col-lg-12">
<div class="row filterPart">
<div class="dropdown filter imm" id="ddlFilter" style="z-index: 2">
<select id="studyTourFilter" class="form-control selectpicker">
<option class="worldSelect" value="" data-content="<img id='studyTourFilterIcon' class='img-responsive icon' src='/assets/img/immigration/flag/world.png'></img> Select Country">Select Country</option>
#foreach (Country country in Model.countryL)
{
#if (country.CountryID == "AUEXP" || country.CountryID == "CAEXP" || country.CountryID == "ITEXP"
|| country.CountryID == "NZEXP" || country.CountryID == "SGEXP" || country.CountryID == "SPEXP")
{
<option id="studyTourOption" value="#Url.Content(country.CountryID)" data-content="<img id='studyTourFilterIcon' class='img-responsive icon' src='#Url.Content(country.CountryImg)'></img> #Url.Content(country.CountryName)">#country.CountryName</option>
}
}
</select>
#foreach (Country country in Model.countryL)
{
#if (country.CountryID == "AUEXP" || country.CountryID == "ITEXP" || country.CountryID == "NZEXP" || country.CountryID == "SGEXP" || country.CountryID == "SPEXP")
{
<div id="tourSelect-#Url.Content(country.CountryID)" class="tourSelect hidden">
<div class="row expcaurosel">
<p id="cauroTitle" class="card-title">Our Packages</p>
#foreach (StudyTour tour in Model.studyTourL)
{
#if (tour.CountryID == country.CountryID)
{
<div class="col-sm-6 col-xs-6 col-md-4 col-lg-4 expCard">
<button id="cauroLinkBtn" type="button" href="#Url.Action("tourPackage", "Experiential", new {id = tour.StudyTourID})" data-toggle="modal" data-target="#staticBackdrop">
#Html.Raw(tour.StudyTourContent)
</button>
</div>
}
}
</div>
</div>
}
}
</div>
</div>
</div>
</div>
<div class="modal fade" id="staticBackdrop" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog modal-xl" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true"><img class="img-responsive" src="/assets/img/experiential/icon/7.png"></span>
</button>
</div>
<div class="modal-body">
**PARTIAL VIEW APPEAR HERE**
<div id="partialView"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#section Scripts {
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/jscript">
$(document).ready(function(){
$("div>button").click(function (e) {
e.preventDefault();
$("#partialView").load($(this).attr("href"));
});
});
</script>
}
Partial View cshtml
#using StiWebsite.Models;
#using System.Security.Policy
#model StudyTourImgPackage;
#{
ViewData["Title"] = "Tour Package Details";
}
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="row title" id="progTitle" style="display: block;">
<div id="packageProgram" class="col-xs-12 col-sm-12 col-md-12 col-lg-12" style="background-color: #fafafa; overflow: hidden">
#Html.Raw(Model.PackageContent)
</div>
</div>
</div>
Controller
using Microsoft.AspNetCore.Mvc;
using StiWebsite.Data;
using StiWebsite.Models;
using System.Dynamic;
namespace StiWebsite.Controllers
{
public class ExperientialController : Controller
{
private ApplicationDbContext _db;
public ExperientialController(ApplicationDbContext db)
{
_db = db;
}
[Route("experiential")]
public IActionResult Experiential()
{
dynamic expModel = new ExpandoObject();
expModel.expL = getExperientialContent();
expModel.studyTourL = getStudyTour();
expModel.tourPackL = getTourPackage();
expModel.countryL = getCountry();
expModel.studyImgPackL = getStudyTourImgPackages();
return View(expModel);
}
//[Route("experiential")]
public PartialViewResult tourPackage(string? id)
{
IEnumerable<StudyTourImgPackage> tourDb = getStudyTourImgPackages();
var detail = tourDb.First(x => x.StudyTourID == id);
return PartialView("tourPackage", detail);
}
public List<StudyTourImgPackage> getStudyTourImgPackages()
{
var expTourList = (from x in _db.TourPackage
select new StudyTourImgPackage
{
PackageID = x.PackageID,
PackageTitle = x.PackageTitle,
PackageContent = x.PackageContent,
PackageIcon = x.PackageIcon,
PackageIconAltText = x.PackageIconAltText,
StudyTourID = x.StudyTourID,
StudyTourTitle = x.StudyTour.StudyTourTitle,
StudyTourContent = x.StudyTour.StudyTourContent,
StudyTourImg = x.StudyTour.StudyTourImg,
StudyTourImgAltText = x.StudyTour.StudyTourImgAltText,
CountryID = x.StudyTour.CountryID,
CountryName = x.StudyTour.Country.CountryName
}).ToList();
return expTourList;
}
}
}

Jquery location picker autocomplete doesn't work in bootstrap modal

I am using jquery location picker inside a bootstrap modal. It opens the map but the autocomplete suggestions are not visible.
The html and the javascript code are given below.
$timeout(function() {
$('#onboardingModal').on('shown.bs.modal', function() {
$('#mappicker').locationpicker({
location: {
latitude: 12.9715987,
longitude: 77.59456269999998
},
radius: 200,
inputBinding: {
locationNameInput: $('#locationInput')
},
enableAutocomplete: true,
autocompleteOptions: {
componentRestrictions: {country: 'in'}
},
onchanged: function (currentLocation, radius, isMarkerDropped) {
var addressComponents = $(this).locationpicker('map').location.addressComponents;
$scope.lat = $(this).locationpicker('map').location.latitude
$scope.lng = $(this).locationpicker('map').location.longitude
// updateControls(addressComponents);
},
});
});
});
<div class="modal fade" id="onboardingModal" tabindex="-1" role="dialog" aria-labelledby="onboardingModalLabel" style="overflow:hidden" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="form-group">
<label for="locationInput">LOCATION</label>
<input type="text" class="form-control" id="locationInput" placeholder="Search"/>
<div align="center" class="map" id="mappicker" style="width: 500px !important; height: 300px"></div>
</div>
</div>
</div>
</div>
Tried changing the z-index also added ui-front class of jquery, didn't work on either case.
What am I doing wrong in this?
I got the answer in one of the issues in github. Needed to add z-index to pac-container.
.pac-container{z-index:2000 !important;}
Reference: Github issue

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:

bootstrap modal box open jquery location picker

I work With jquery location picker plugin for google map. now, I open map into bootstrap 3.0 modal box. This worked, But I need to: when click in save changes button show longitude and latitude in result input box.
JS:
$('#us2').locationpicker({
location: {
latitude: 46.15242437752303,
longitude: 2.7470703125
},
radius: 300,
inputBinding: {
latitudeInput: $('#us2-lat'),
longitudeInput: $('#us2-lon'),
radiusInput: $('#us2-radius'),
locationNameInput: $('#us2-address')
}
});
$(document).ready(function () {
$("#btnModal").click(function () {
//How Can I Copy myDiv here so that I can also view it in Modal
$("#myModal").modal('show');
$("#myDiv").appendTo(".modal-body");
});
$('#myModal').on('hide.bs.modal', function (e) {
$("#myDiv").prependTo("body");
})
});
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="width: 500px; 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>
result lat: <input type="text" id="lat" />
result long: <input type="text" id="lon" />
I have result long and result lat for input/join value form modal box when click in save changes button. How to create This ?
DEMO : http://jsfiddle.net/hagR2/
Give the "save changes" btn an id :
Save changes
add a click handler to the btn that transfers the values to the main page and closes the modal :
$("#save-changes").click(function() {
$("#lat").val($('#us2-lat').val());
$("#lon").val($('#us2-lon').val());
$('#myModal').modal('hide');
})
forked fiddle -> http://jsfiddle.net/Lzv7w/
Try this out:- http://jsfiddle.net/adiioo7/hagR2/2/
JS:-
$('#us2').locationpicker({
location: {
latitude: 46.15242437752303,
longitude: 2.7470703125
},
radius: 300,
inputBinding: {
latitudeInput: $('#us2-lat'),
longitudeInput: $('#us2-lon'),
radiusInput: $('#us2-radius'),
locationNameInput: $('#us2-address')
}
});
$(document).ready(function () {
$("#btnModal").click(function () {
//How Can I Copy myDiv here so that I can also view it in Modal
$("#myModal").modal('show');
$("#myDiv").appendTo(".modal-body");
});
$('#btnSave').on('click', function (e) {
$("#lat").val($("#us2-lat").val());
$("#lon").val($("#us2-lon").val());
})
});

Categories