Move google map marker on bootstrap carousel slide - javascript

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>

Related

How can I update markers, retrieved from firestore, on my map without reloading the page?

I am retrieving markers stored in my firestore collection and want to see the changes occur in real-time without having to reload the page to see my changes.
My original method involved using get() from which I need to reload in order to see my changes
db.collection('Limuru').get().then((snapshot) => {
snapshot.forEach(function(child){
addMarker();
})
});
I then used OnSnapshot() instead of get() .
db.collection('Limuru').onSnapshot(function(snapshot) {
snapshot.forEach(function(child){
addMarker();
})
});
The data was changing in real-time, however the behaviour was strange as every time there was a change, more markers were added and not being replaced.
How can I restructure my code to make this work the way I want it to? Should I use AJAX or change my logic for the OnSnapshot Method?
Full code below:
<script src="https://www.gstatic.com/firebasejs/7.2.3/firebase-app.js"></script>
<script defer src="https://www.gstatic.com/firebasejs/7.2.3/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.2.3/firebase-firestore.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OverlappingMarkerSpiderfier/1.0.3/oms.min.js"></script>
<link rel="stylesheet" type="text/css" href="map.css">
<link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="navbar.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<nav class="navbar navbar-dark bg-primary fixed-top" role="navigation">
<a class="navbar-brand" href="#">Radio Africa</a>
<a class="navbar-brand" id="loggedin"></a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="./admin-map.php">Maps <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Error reports </a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Locations
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="./stations.php">Nairobi</a>
<a class="dropdown-item" href="./limuru.php">Limuru</a>
<a class="dropdown-item" href="./machakos.php">Machakos</a>
</div>
</li>
</div>
</nav>
<div id="map"></div>
<!------ Include the above in your HEAD tag ---------->
<script>
firebase.initializeApp({
apiKey: "xxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxx",
});
const db = firebase.firestore();
db.settings({timestampsInSnapshots: true});
var map;
var marker;
var infowindow;
var green_icon = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png' ;
var red_icon = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png' ;
var isBouncing;
function initMap() {
var options = {
zoom: 9,
center: {lat: -1.2921, lng: 36.8219}
};
var map = new google.maps.Map(document.getElementById('map'),options);
var oms = new OverlappingMarkerSpiderfier(map, {
markersWontMove: true,
markersWontHide: true,
basicFormatEvents: true,
keepSpiderfied: true,
circleFootSeparation : 50,
});
function addMarker(coords, content, animation){
var marker = new google.maps.Marker({
position: coords,
map: map,
icon: icon = {
url : isBouncing ? red_icon : green_icon,
scaledSize: new google.maps.Size(40, 40), // scaled size
// origin: new google.maps.Point(0,0), // origin
// anchor: new google.maps.Point(0, 0) // anchor
},
// IF THERE'S AN ERROR, BOUNCE IT
animation: animation
});
var infoWindow = new google.maps.InfoWindow({
content: content
});
marker.addListener('spider_click', function() {
map.panTo(this.getPosition());
infoWindow.open(map,marker);
});
oms.addMarker(marker);
}
db.collection('Limuru').onSnapshot(function(snapshot) {
snapshot.forEach(function(child){
var name_loc = child.id;
var loc = child.data().marker;
var forward = child.data().ForwardPower;
var reflected = child.data().ReflectedPower;
var ups = child.data().UPSError;
var upsDesc = child.data().UPSDesc;
var trans = child.data().TransmitterError;
var transDesc = child.data().TransDesc;
var kplc = child.data().KPLC;
var kplcDesc = child.data().KPLCDesc;
var sat = child.data().SatelliteReceiver;
var satDesc = child.data().SatDesc;
if(ups === true && trans ===true && sat ===true && kplc ===true){
isBouncing = true;
addMarker(
{lat: loc.latitude, lng: loc.longitude },
'' +
'<div id="iw-container">' +
`<div class="iw-title"> ${name_loc}</div>` +
'<div class="iw-content">' +
"<br/>"
+ `<p> UPSError: ${upsDesc} </p>`
+ `<p> SatelliteReceiver: ${satDesc} </p>`
+ `<p> KPLC: ${kplcDesc} </p>`
+ `<p> TransmitterError: ${transDesc} </p>`
+ '</div>' +
'<div class="iw-bottom-gradient"></div>' +
'</div>'
,google.maps.Animation.BOUNCE
);
}
})
)}
}
<script async defer
src="https://maps.googleapis.com/maps/api/js?language=en&key=xxxxxxxxxxxxx&callback=initMap">
</script>
If I understand correctly your question, this is because each time the listener is triggered you receive ALL the docs in the Limuru collection.
You basically have two options:
Option 1: Re-initialize your list of markers
I.e. removing all of them and re-creating them
Option 2: Listen to actual changes
As explained in the doc, you can detect "the actual changes to query results between query snapshots".
For example, you could only handle the additions, as follows:
db.collection('Limuru').onSnapshot((querySnapshot) => {
querySnapshot.docChanges().forEach((change) => {
if (change.type === "added") {
addMarker();
}
if (change.type === "removed") {
//Remove marker
//https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/marker-remove
//https://developers.google.com/maps/documentation/javascript/markers#remove
}
//.....
});
//....
});

HTML Javascript function only works on second click

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>

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 () { /// }

JQuery - Change value of Name, Longitude, and Latitude location in google maps api

I am trying to implement a feature on my site where certain list of places are displayed next to a Map that when a user selects a place in the list it automatically sets the Name, Longitude, and Latitude on the map for the user to identify where it is.
Unfortunately, I got stuck in changing the value of the Name, Longitude, and Latitude in the map if the user selects a different place in the list.
I referred to this stackoverflow question
so far I have come up with this code.
HTML
<div class="col-md-12">
<div class="col-md-3">
<div class="list-group">
Cras justo odio
Dapibus ac facilisis in
Morbi leo risus
Porta ac consectetur ac
Vestibulum at eros
</div>
</div>
<div class="col-md-9">
<div id="map"></div>
</div>
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
function initMap(mapLocation) {
var map = new google.maps.Map(document.getElementById('map'), {
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 < mapLocation; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(mapLocation[i][1], mapLocation[i][2]),
map: map
});
}
}
$('.list-group-item').on('click', function (e) {
var previous = $(this).closest(".list-group").children(".active");
previous.removeClass('active'); // previous list-item
$(e.target).addClass('active'); // activated list-item
var locations = $('.list-group').find('.active').data('itemtype');
initMap(locations);
});
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB3qsbdbcouUb6qSaBxQCuiEDI03JA-zLc&callback=initMap">
</script>
please help me to be on track with the development.
Thank you in advance
A solution using data attributes. I modified your data attributes slightly because using...
data-itemtype="['Maroubra Beach', '-33.950198', '151.259302']"
...doesn't give you an array to use, just a string that looks like an array.
HTML:
<div class="container">
<div class="row">
<div class="list-group col-sm-2">
<a id="0" href="#" class="list-group-item" data-name='Maroubra Beach' data-lat='-33.950198' data-lng='151.259302'>Cras justo odio</a><br />
<a id="1" href="#" class="list-group-item" data-name='Coogee Beach' data-lat='-33.923036' data-lng='151.259052'>Dapibus ac facilisis in</a><br />
<a id="3" href="#" class="list-group-item" data-name='Cronulla Beach' data-lat='-34.028249' data-lng='151.157507'>Morbi leo risus</a>
</div>
<div class="col-sm-10">
<div id="map_canvas"></div>
</div>
</div>
</div>
Javacript:
(function(Mapping, $, undefined) {
var self = this;
function Initialize() {
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
self.map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
self.infoWindow = new google.maps.InfoWindow();
$('.list-group-item').each(function() {
var $this = $(this);
var pos = new google.maps.LatLng($this.data('lat'), $this.data('lng'));
var marker = new google.maps.Marker({
position: pos,
map: self.map
});
$this.click(function() {
self.map.panTo(pos);
self.infoWindow.setContent($this.data('name'));
self.infoWindow.open(self.map, marker);
$this.siblings().removeClass('active');
$this.addClass('active');
});
});
}
Initialize();
})(window.Mapping = window.Mapping || {}, jQuery);
JSFiddle

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