HTML Javascript function only works on second click - javascript

I am trying to show a google map on a bootstrap tab, however the map only shows correctly when the tab is clicked on the second time. On the first click, there is a lot of grey area and the map needs to resize.
I've looked at this but nothing there helps.
js:
<script type="text/javascript">
$('a[href="#sectionB"]').on('shown', function (e) {
initMap();
});
function initMap() {
var uluru = {lat: -34.031342, lng: 18.577419};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: uluru,
mapTypeId: 'satellite'
});
var marker = new google.maps.Marker({
position: {lat: -34.031342, lng: 18.577419},
map: map
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MYKEYHERE&callback=initMap">
</script>
html:
<div class="col-md-12">
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#sectionA">Details</a></li>
<li><a data-toggle="tab" id = "sectionb" href="#sectionB" onclick="initMap(); return false;">Location</a></li>
</ul>
<div class="tab-content">
<div id="sectionA" class="tab-pane fade in active">
<div class="col-md-8" style = "padding-top: 3%">
</div>
</div>
<div id="sectionB" class="tab-pane fade">
<div class="row">
<div class="col-md-8">
<div id ="map" style="width:400px;height:400px;">
</div>
</div>
</div>

Related

Rails: Fit to bounds google map

I have a map inside a dynamic tab:
<div id="tabs">
<div class="panel with-nav-tabs panel-default">
<div class="panel-heading">
<ul class="nav nav-tabs" id="prodTabs">
<li class="active">Map_locations</li>
<li>Comments</li>
<% if shopper_signed_in? %>
<li>Add Comments</li>
<% end %>
</ul>
</div>
<div class="panel-body">
<div class="tab-content">
<div class="tab-pane active" id="map">
<div id="map"></div>
the tabs are dynamic:
<script>
$('#tabs').on('click','.tablink,#prodTabs a',function (e) {
e.preventDefault();
var url = $(this).attr("data-url");
if (typeof url !== "undefined") {
var pane = $(this), href = this.hash;
// ajax load from data-url
$(href).load(url,function(result){
pane.tab('show');
});
} else {
$(this).tab('show');
}
});
</script>
and I'm trying to show the map fit to bounds according to the two markers I have. But one marker is showing half, and only if I zoom out the map appears correct. But I don't want the value of the zoom to be so zoomed out. Any ideas on how to fix this issue?
<script>
handler = Gmaps.build('Google');
handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
markers = handler.addMarkers(<%=raw #hash.to_json %>);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
handler.getMap().setZoom(15);
});
</script>

Move google map marker on bootstrap carousel slide

I am trying to move marker on bootstrap carousel slide change. I have successfully generated a map with marker and successful in binding the slide to call a function. So when users slide over the addresses google map should show the marker for that particular location. Here is what i tried :
<script type="text/javascript" >
google.maps.event.addDomListener(window, 'load', myMap);
function myMap() {
var mapProp = {
center:new google.maps.LatLng(-27.4698,153.0251),
zoom:11,
styles: [{featureType:"landscape",stylers:[{saturation:-100},{lightness:65},{visibility:"on"}]},{featureType:"poi",stylers:[{saturation:-100},{lightness:51},{visibility:"simplified"}]},{featureType:"road.highway",stylers:[{saturation:-100},
{visibility:"simplified"}]},{featureType:"road.arterial",stylers:[{saturation:-100},{lightness:30},{visibility:"on"}]},{featureType:"road.local",stylers:[{saturation:-100},{lightness:40},{visibility:"on"}]},{featureType:"transit",stylers:[{saturation:-100},
{visibility:"simplified"}]},{featureType:"administrative.province",stylers:[{visibility:"off"}]/**/},{featureType:"administrative.locality",stylers:[{visibility:"off"}]},{featureType:"administrative.neighborhood",stylers:[{visibility:"on"}
]/**/},{featureType:"water",elementType:"labels",stylers:[{visibility:"on"},{lightness:-25},{saturation:-100}]},{featureType:"water",elementType:"geometry",stylers:[{hue:"#ffff00"},{lightness:-25},{saturation:-97}]}]
};
var turbot = new google.maps.LatLng(-27.456730,153.029497);
var marker = new google.maps.Marker({
position:turbot,
animation:google.maps.Animation.BOUNCE,
icon: 'images/marker.png'
});
var map = new google.maps.Map(document.getElementById("map"),mapProp);
marker.setMap(map);
}
function updateMarker( map, marker ) {
marker.setPosition( new google.maps.LatLng( -33.8688, 151.2093 ) );
map.panTo( new google.maps.LatLng( -33.8688, 151.2093 ) );
}
</script>
Here i am declaring a function after myMap() which is updateMarker() then tried to call updateMarker() on slide change as follows :
jQuery('#myCarousel').bind('slide.bs.carousel', function (e) {
updateMarker();
});
But it looks like that updateMarker() don't know map and marker objects. It says:
***Uncaught TypeError: Cannot read property 'setPosition' of undefined
Any help ? I am sure i am declaring that function on a wrong place. any help please
You forgot to pass map and marker arguments to updateMarker function.
Here is an modified example that demonstrates how update marker position to on carousel slide change
google.maps.event.addDomListener(window, 'load', initMap);
function initMap() {
var locations = [
{ "lat": 40.7055646, "lng": -74.1184291 },
{ "lat": 37.7576948, "lng": -122.4727052 }
];
var mapProps = {
zoom: 4
};
var map = new google.maps.Map(document.getElementById("map"), mapProps);
var marker = new google.maps.Marker({
animation: google.maps.Animation.BOUNCE
});
marker.setMap(map);
updateMarker(map,marker,locations[0]);
$('#myCarousel').bind('slide.bs.carousel', function (e) {
var slideIdx = $(e.relatedTarget).index();
updateMarker(map,marker, locations[slideIdx]);
});
}
function updateMarker(map, marker, pos) {
marker.setPosition(new google.maps.LatLng(pos.lat, pos.lng));
map.panTo(marker.getPosition());
}
.item {
height: 90px;
}
.carousel {
height: 60px;
}
#map {
height: 240px;
}
<script type="text/javascript" src="//code.jquery.com/jquery-2.0.2.js"></script>
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<script type="text/javascript" src="//netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1" class=""></li>
</ol>
<div class="carousel-inner">
<div class="item active">
<div class="container">
<div class="carousel-caption">
<h1>New York</h1>
</div>
</div>
</div>
<div class="item">
<div class="container">
<div class="carousel-caption">
<h1>San Francisco</h1>
</div>
</div>
</div>
</div>
<!-- Carousel controls -->
<a class="left carousel-control" href="#myCarousel" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span></a>
<a class="right carousel-control" href="#myCarousel" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a>
</div>
<div id="map"></div>

how to use google map in angularjs with script of key Without Google SDK

i don't want Google SDK, i have following code..i but its show error when i use tag its working fine but i am using angularjs its show error , normal page with script in page its working fine..how to define initMap method in angular
ReferenceError: google is not defined
export default class locationComponent {
/*#ngInject*/
constructor($http, $scope, $q, socket, $document) {
this.$http = $http;
this.$scope = $scope;
this.$q = $q;
this.socket = socket;
this.$document = $document;
this.initMap();
}
initMap() {
var myLatLng = new google.maps.LatLng(parseFloat(-25.363),parseFloat(131.044)); //{lat: inputlng, lng: inputlat};
console.log('latutye');
var map = new google.maps.Map(document.getElementById('mapsss'), {
zoom: 15,
center: myLatLng,
mapTypeIds: ['roadmap', 'terrain']
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
}
<div class="inner-wrapper">
<section role="main" class="content-body">
<header class="page-header">
<h2> Current Location</h2>
<div class="right-wrapper pull-right">
<ol class="breadcrumbs">
<li>
<a href="/dashboard">
<i class="fa fa-home"></i>
</a>
</li>
<li><span></span></li>
<li><span>Location</span></li>
</ol>
<a class="sidebar-right-toggle" data-open="sidebar-right"><i class="fa fa-chevron-left"></i></a>
</div>
</header>
<div class="modal-backdrop fade in" id="loading_div" style="display:none;">
<div class="loader"></div>
</div>
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
<div class="panel-actions">
</div>
<h2 class="panel-title"> Current Location </h2>
</header>
<div class="panel-body">
<div class="form-group">
<div style="height: 500px;" id="mapsss" class="panel-body">
</div>
</div>
</div>
</section>
</div>
</div>
</section>
</div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR KEY&callback=initMap">
</script>
Use this in controller
$window.initMap = function () { /// }

Don't show Google map with Gmaps.js

I want to use Google map in my we page. i used Gmaps.js for it. my code is bellow:
<div class="row col-md-10 col-md-offset-1">
<br>
<br>
<br>
<label for="address">{{$MapLabel}}</label>
<div class="span11">
<div id="map"></div>
</div>
<br>
<br>
<div class="row">
<div class="col-md-4">
<button id="button_Google_Serach" type="button" class="btn btn-info" >جستجو</button>
</div>
<div class="col-md-8">
<input type="text" id="address_with_google" name="address_with_google" placeholder="{{$SearchLabel}}" class="form-control" />
</div>
</div>
<input type="text" hidden id="latGoogleMap">
<input type="text" hidden id="lngGoogleMap">
<br>
</div>
when i write bellow code, i don't see any google map div same bellow image.
var map;
$(document).ready(function(){
map = new GMaps({
el: '#map',
lat: -12.043333,
lng: -77.028333,
zoom: 16,
click: function(e){
map.removeMarkers();
map.addMarker({
lat: e.latLng.lat(),
lng: e.latLng.lng(),
draggable: true
});
//Set google lat in hidden input
$('#latGoogleMap').val( e.latLng.lat());
//Set google lng in hidden input
$('#lngGoogleMap').val(e.latLng.lng());
}
});
});
but when i remove that code i see this:
How must i do?
Use height and widthfor google map:
map = new GMaps({
el: '#map',
lat: -12.043333,
lng: -77.028333,
width: '95%',
height: '350px',
zoom: 16,
click: function(e){
map.removeMarkers();
map.addMarker({
lat: e.latLng.lat(),
lng: e.latLng.lng(),
draggable: true
});
//Set google lat in hidden input
$('#latGoogleMap').val( e.latLng.lat());
//Set google lng in hidden input
$('#lngGoogleMap').val(e.latLng.lng());
}
});

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:

Categories