Infobubble Keep Adding tab and Not removing the previous tab added - javascript

I encountered this problem and I'm new on using Infobubble for Google Maps and when i click the marker and add tab, when i change the marker clicked the Previous tab still show
all i want is to remove the previous tab.
This is my Snippet:
function codeAddress() {
infoBubble = new InfoBubble({
map: map,
shadowStyle: 0,
padding: 10,
borderRadius: 10,
arrowSize: 15,
maxWidth: 300,
borderWidth: 1,
borderColor: '#ccc',
arrowPosition: 30,
arrowStyle: 0
});
$.getJSON('/Dashboard/LoadWorkerList', function (address) {
$.each(address, function () {
var currVal = this["AddressLine1"];
var Name = this["Name"];
var Gender = this["Gender"];
var Bdate = this["Birthdate"];
geocoder.geocode({ 'address': currVal }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
icon: iconBase + 'man.png',
position: results[0].geometry.location,
title: currVal
})
$('#places').append($('<li>')
.text(currVal)
.data('location', results[0].geometry.location));
google.maps.event.addListener(map, 'bounds_changed', function () {
$('#places li').css('display', function () {
return (map.getBounds().contains($(this).data('location')))
? ''
: 'none';
});
});
//mgr = new MarkerManager(map);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infoBubble.addTab(Name, Name + "" + currVal + "" + Gender + "" + Bdate);
infoBubble.open(map, marker);
}
})(marker, currVal));
address.push(marker);
}
else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(codeAddress, 2000);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
google.maps.event.trigger(map, 'bounds_changed');
});
}
As you can see. the tab for Britney Spears is there on the marker of Miley Cyrus.
All i want is to remove the first clicked marker tab

why don't you try something like this instead of adding tabs to one infowindow and changing it's location each time?
var myLatlng = new google.maps.LatLng(latValue, longValue);
var mapOptions = {
...
center: myLatlng
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var infoBubble = null;
...
google.maps.event.addListener(marker, 'click', function() {
if (infoBubble) {
infoBubble.close();
}
infoBubble = new google.maps.InfoWindow({content: singersTextContent});
infoBubble.open(map, marker);
...
});

Related

adding infowindow to google maps

I'm trying to add some infowindow content to my markers on a google map. I can query my server, get some data, put the markers on the map. That works. What doesn't work is that nothing happens when I click on the marker. I would think that the infowindow would popup. Unfortunately, it has been so long since I have done google maps programming, I am effectively starting over. For some reason, the marker's click event is not being called. Any suggestions regarding my dumbness are appreciated. TIA
<script>
var map, geocoder;
var Markers = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 0.0, lng: 0.0 },
zoom: 12
});
if (!Modernizr.geolocation) {
alert("Your browser sucks. Get a new one, maybe one that is up to date and supports GPS.")
return;
}
else {
navigator.geolocation.getCurrentPosition(show_map);
}
}
function show_map(position) {
map.setZoom(12);
var Latitude = position.coords.latitude;
var Longitude = position.coords.longitude;
map.setCenter({ lat: Latitude, lng: Longitude });
var bounds = map.getBounds();
var url = "/api/xxxxxxxxjsonendpoint";
var lowerLeft = bounds.getSouthWest();
var upperRight = bounds.getNorthEast();
var lat0 = lowerLeft.lat();
var lng0 = lowerLeft.lng();
var lat1 = upperRight.lat();
var lng1 = upperRight.lng();
var geocoder = new google.maps.Geocoder();
var data = { LowerLeftLat: lat0, LowerLeftLng: lng0, UpperRightLat: lat1, UpperRightLng: lng1 };
$.get(url, data, function (result) {
for (var i = 0; i < result.length; i++) {
var address = result[i].Address1 + " " + (result[i].Address2 != null ? result[i].Address2 : "") + " " + result[i].City + " " + result[i].Province + " " + result[i].PostalCode + " " + result[i].Country;
var marker = new google.maps.Marker({
position: geocodeAddress(geocoder, map, address),
map: map,
title: address
});
var infowindow = new google.maps.InfoWindow({
content: i
});
makeInfoWindowEvent(map, infowindow, "test" + i, marker);
}
});
}
function geocodeAddress(geocoder, resultsMap, address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
</script>
Here is the most recent update of my code. Still no worky........
<script>
var map, geocoder;
var Markers = [];
var infowindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 0.0, lng: 0.0 },
zoom: 12
});
infowindow = new google.maps.InfoWindow();
if (!Modernizr.geolocation) {
alert("Your browser sucks. Get a new one, maybe one that is up to date and supports GPS.")
return;
}
else {
navigator.geolocation.getCurrentPosition(show_map);
}
}
function show_map(position) {
map.setZoom(12);
var Latitude = position.coords.latitude;
var Longitude = position.coords.longitude;
map.setCenter({ lat: Latitude, lng: Longitude });
var bounds = map.getBounds();
var url = "/api/xxxxxxx/yyyyyyyyyy";
var lowerLeft = bounds.getSouthWest();
var upperRight = bounds.getNorthEast();
var lat0 = lowerLeft.lat();
var lng0 = lowerLeft.lng();
var lat1 = upperRight.lat();
var lng1 = upperRight.lng();
var geocoder = new google.maps.Geocoder();
var data = { LowerLeftLat: lat0, LowerLeftLng: lng0, UpperRightLat: lat1, UpperRightLng: lng1 };
$.get(url, data, function (result) {
for (var i = 0; i < result.length; i++) {
var address = result[i].Address1 + " " +
(result[i].Address2 != null ? result[i].Address2 : "") +
" " + result[i].City + " " + result[i].Province + " " +
result[i].PostalCode + " " + result[i].Country;
var marker = new google.maps.Marker({
position: geocodeAddress(geocoder, map, address),
map: map,
title: address,
content: address
});
makeInfoWindowEvent(infowindow, "test" + i, marker);
}
});
}
function geocodeAddress(geocoder, resultsMap, address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function makeInfoWindowEvent(infowindow, contentString, marker) {
(function (zinfowindow, zcontentString, zmarker) {
zinfowindow.setContent(zcontentString);
google.maps.event.addListener(zmarker, 'click', function () {
zinfowindow.open(map, zmarker);
});
})(infowindow, contentString, marker);
}
</script>
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
infowindow.setContent(contentString);
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
Your code crash because when the listener is calling, the value of marker and infowindow have already changed. You can try something like this (just change the makeInfoWindowEvent function):
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(contentString);
infowindow.open(map, marker);
console.log (contentString);
console.log (marker);
});
}
Normally, the output will be always the same for contentString and marker.
In order to pass the real value of the marker, contentString and infowindow, you have to create an IIFE. Like this, the value of the variables will be copy inside the function:
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
(function (zinfowindow, zcontentString, zmarker) {
zinfowindow.setContent(zcontentString);
google.maps.event.addListener(zmarker, 'click', function () {
zinfowindow.open(map, zmarker);
});
})(infowindow, contentString, marker);
}
However, you do not need to pass map as parameter because the value of map is always the same.
Tell me if you have some questions.

Uncaught TypeError: Cannot read property 'PlacesService' of undefined in google map api

doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
script(src='/javascripts/jquery.min.js')
script(src='http://maps.google.com/maps/api/js?key=AIzaSyD6MCxtDJOnbE1T6Y09k8Uca1rXHTQ3Bqg&v=3.exp&sensor=true&libraries=place‌​s')
script(src='/javascripts/global.js')
h1= title
#loading
p Loading your location
br
#map
input#my-address(type='text')
button#getCords(onclick='codeAddress();') getLat&Long
I write above code in jade template for display the map i.e 'index.jade' and
following file i.e 'global.js' is script file
//Calling the locateme function when the document finishes loading
$(document).ready(function() {
locateMe();
});
//Function to locate the user
var locateMe = function(){
var map_element= $('#map');
if (navigator.geolocation) {
var position= navigator.geolocation.getCurrentPosition(loadMap);
} else {
map_element.innerHTML = "Geolocation is not supported by this browser.";
}
};
//Lets load the mop using the position
var loadMap = function(position) {
var loading= $('#loading');
var latitude=position.coords.latitude;
var longitude=position.coords.longitude;
var myLatlng = new google.maps.LatLng(latitude, longitude);
//Initializing the options for the map
var myOptions = {
center: myLatlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
//Creating the map in teh DOM
var map_element=document.getElementById("map");
var map = new google.maps.Map(map_element,myOptions);
//Adding markers to it
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'You are here'
});
//Adding the Marker content to it
var infowindow = new google.maps.InfoWindow({
content: "<h2>You are here:</h2>",
//Settingup the maxwidth
maxWidth: 300
});
//Event listener to trigger the marker content
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);});
};
//get lat and log
function codeAddress() {
alert('inside')
geocoder = new google.maps.Geocoder();
var address = document.getElementById("my-address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat=results[0].geometry.location.lat();
var lng=results[0].geometry.location.lng();
var pyrmont={lat:lat,lng:lng};
var lat=results[0].geometry.location.lat();
var lng=results[0].geometry.location.lng();
var pyrmont={lat:lat,lng:lng};
var map = new google.maps.Map(document.getElementById("my-address"),{
center:pyrmont,
zoom:15
});
//Adding the Marker content to it
var infowindow = new google.maps.InfoWindow();
alert(infowindow);
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
type: ['store']
}, callback);
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
};
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Uncaught TypeError: Cannot read property 'PlacesService' of undefined in google map api
You are doing Place Search which doesnt return all of the fields that you are using:
http://code.google.com/apis/maps/documentation/javascript/places.html#place_search_responses
In order to get the address, website, etc, you'll also need to call place.getDetails(), passing the Place's reference.
Below is a sample code snippet how to get Places details:
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var request = { reference: place.reference };
service.getDetails(request, function(details, status) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(details.name + "<br />" + details.formatted_address +"<br />" + details.website + "<br />" + details.rating + "<br />" + details.formatted_phone_number);
infowindow.open(map, this);
});
});
}

Google maps infowindow error f = undefined infowindow.js

I've got a weird problem. It says f = undefined in infowindow.js. But I don't even have a file infowindow.js... This happens when I click on it. It has to show infowindow, but it doesn't.
Got the code from documentation here: LINK
Here's my code (address array is now adjusted, in my code there are normal addresses in it):
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: { lat: 52.3, lng: 5.7 }
});
var geocoder = new google.maps.Geocoder();
var addresses = [
{
'adres': 'teststraat 21',
'plaats': 'Apeldoorn',
'postcode': '1234AB',
'telefoon': '0123456789',
'openingstijden': 'test'
},
{
'adres': 'teststraat 21',
'plaats': 'Apeldoorn',
'postcode': '1234AB',
'telefoon': '0123456789',
'openingstijden': 'test'
},
{
'adres': 'teststraat 21',
'plaats': 'Apeldoorn',
'postcode': '1234AB',
'telefoon': '0123456789',
'openingstijden': 'test'
},
];
geocodeAddress(geocoder, map, addresses);
}
function geocodeAddress(geocoder, resultsMap, addresses) {
for(var i = 0; i < addresses.length; i++) {
geocoder.geocode({'address': addresses[i]['adres'] + addresses[i]['plaats']}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var counter = i - addresses.length;
var infowindow = new google.maps.InfoWindow({
content: 'test',
maxWidth: 200
});
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location,
title: 'testadres ' + addresses[counter]['plaats'],
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
i++;
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
You use map instead of resultsMap in this piece of code:
The map object doesn't exist in this context. Should be:
infowindow.open(resultsMap, marker);
To close the staying infowindow before opening a new one, add only one infowindow instance and change it's content and position on marker click:
var infowindow = null;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: { lat: 52.3, lng: 5.7 }
});
var geocoder = new google.maps.Geocoder();
var addresses = [];
geocodeAddress(geocoder, map, addresses);
}
function geocodeAddress(geocoder, resultsMap, addresses) {
var infowindow = new google.maps.InfoWindow();
for(var i = 0; i < addresses.length; i++) {
geocoder.geocode({'address': addresses[i]['adres'] + " " + addresses[i]['plaats']}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var counter = i - addresses.length;
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location,
title: 'testadres ' + addresses[counter]['plaats'],
});
marker.addListener('click', function() {
infowindow.setContent('test content');
infowindow.open(resultsMap, marker);
});
i++;
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
<div id="map" style="height:400px; width:500px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
async defer></script>

Working with two google maps

Hi I need some help with the following:
I am trying to get two maps to display two different things.
My problem is, on the first map I would like to click on a link in the infowindow (see this) when I do click on that link, I would like that marker to display alone on the second map at its location.
here is my code. Thank you for any help.
$(document).ready(function() {
var map;
var service;
function initialise(location) {
console.log("location:" + location);
var currentLocation = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
var mapOption = {
center : currentLocation,
zoom : 14,
mapTypeId : google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOption);
var marker = new google.maps.Marker({
position : currentLocation,
map : map,
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
//service = new google.maps.places.PlacesService(map);
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
function handleSearchResults(results, status) {
console.log(results)
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map : map,
position : place.geometry.location
});
var content = '<p>See this</p>'
var infowindow = new google.maps.InfoWindow({
content:('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address + content)
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
var latitude = this.position.lat();
var longitude = this.position.lng();
console.log(this.position);
});
}
google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
var input = $("#search").val();
var query = (input != '' )? input : "restaurant";
performSearch(query);
});
function performSearch(q){
var request ={
bounds: map.getBounds(),
query:String(q)
};
service.textSearch(request, callback);
}
}
function initializer() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
});
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
var marker = new google.maps.Marker({
position : initialLocation,
map : map,
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
}, function() {
handleNoGeolocation(browserSupportFlag);
});
}
}
function initializer_2() {
var mapOption2 = {
center : new google.maps.LatLng(41.923, 12.513),
zoom : 14,
mapTypeId : google.maps.MapTypeId.ROADMAP,
};
var marker = new google.maps.Marker({
// need the position of marker
//position : currentLocation,
map : map,
});
map = new google.maps.Map(document.getElementById("map-canvas2"), mapOption2);
}
google.maps.event.addDomListener(window, 'load', initializer);
google.maps.event.addDomListener(window, 'load', initializer_2);
$(".getSearch").click(function () {
navigator.geolocation.getCurrentPosition(initialise);
});
});

infoBubble nothing display on gmappanel - EXTJS 4

function addDoctorLocation(options)
{
var gm = Ext.getCmp('mygooglemap');
var mpoint = new google.maps.LatLng(options.lat,options.lng);
var marker = gm.addMarker(mpoint,options.marker,false,false, options.listeners);
infoBubble = new InfoBubble({
map: gm,
content: '<div class="phoneytext">Some label</div>',
//position: new google.maps.LatLng(options.lat, options.lng),
shadowStyle: 1,
padding: '10px',
//backgroundColor: 'rgb(57,57,57)',
borderRadius: 5,
minWidth: 200,
arrowSize: 10,
borderWidth: 1,
borderColor: '#2c2c2c',
disableAutoPan: true,
hideCloseButton: false,
arrowPosition: 7,
backgroundClassName: 'phoney',
pixelOffset: new google.maps.Size(130, 120),
arrowStyle: 2
});
infoBubble.open(map, marker);
}
Success added the marker on map, unfortunately infoBubble nothing has shown? why?
and dont have any error on FireBug
UPDATE HOW TO CALL THE FUNCTION
tree.on('checkchange', function(node){
var data = node.data;
if (data.checked == true){
var lati,longi;
var record = MarkerStore.findRecord('MainID', data.MainID)
if (record){
lati = record.get('Latitude');
longi = record.get('Longitude');
}else{
Ext.MessageBox.show({
title: 'Error !',
msg: 'No Record Found In Database ! <br />',
icon: Ext.MessageBox.INFO
});
}
var options = {
lat:lati,
lng:longi,
marker: {title:"Hello World!"},
listeners: {
click: function(e){
}
},
MainID: data.MainID
}
addDoctorLocation(options);
} else {
markers[data.MainID].setMap(null);
}
})
UPPDATE For #Ankit
var markers = {};
var openedInfoWindow = null;
function addDoctorLocation(options)
{
var gm = Ext.getCmp('mygooglemap');
var mpoint = new google.maps.LatLng(options.lat,options.lng);
var marker = gm.addMarker(mpoint,options.marker,false,false, options.listeners);
markers[options.MainID] = marker;
var infowindow = new google.maps.InfoWindow({
content: 'Hello !',
maxWidth: 200
});
google.maps.event.addListener(marker, 'click', function() {
// added next 4 lines
google.maps.event.addListener(infowindow, 'closeclick', function() {
openedInfoWindow = null;
});
if (openedInfoWindow != null) openedInfoWindow.close(); // <-- changed this
openedInfoWindow = infowindow;
infowindow.open(gm, marker);
});
still can't close the infowindow,when clicked marker get this error
TypeError: b.O is not a function
[Break On This Error]
(82 out of range 43)
function addDoctorLocation(options)
{
var gm = Ext.getCmp('mygooglemap');
var mpoint = new google.maps.LatLng(options.lat,options.lng);
var marker = gm.addMarker(mpoint,options.marker,false,false, options.listeners);
var infowindow = new google.maps.InfoWindow({content: "Some label"});
google.maps.event.addListener(marker, 'click', function(gm,marker) {
infowindow.open(gm, marker); // if still you can not open than use infowindow.open(gm, this)
})
}
but looks like you want to style your infowindow than better use infobox instead of infowindow. Check you about InfoBox ->Styling InfoWindow with Google Maps API
You can add some html tags like br, bold to infowindow content but I think you can not style infowindow.
I try your example with google maps intstance and it works fine:
var markers = {};
var infowindow;
var openedInfoWindow = null;
var centerPointDefault = new google.maps.LatLng(39.739, -98.984);
function DrawMainMap(centerMap) {
var myOptions = {
center: centerMap,
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
}
$(document).ready(function () {
var options = {
lat: centerPointDefault.lat(),
lng: centerPointDefault.lng(),
marker: { title: "Hello World!" },
listeners: {
click: function(e) {
}
}
};
DrawMainMap(centerPointDefault);
addDoctorLocation(options);
}
function addDoctorLocation(options) {
var mpoint = new google.maps.LatLng(options.lat, options.lng);
var marker = new google.maps.Marker({
position: mpoint
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content: 'Hello !',
maxWidth: 200
});
google.maps.event.addListener(marker, 'click', function() {
// added next 4 lines
google.maps.event.addListener(infowindow, 'closeclick', function() {
openedInfoWindow = null;
});
if (openedInfoWindow != null) openedInfoWindow.close(); // <-- changed this
openedInfoWindow = infowindow;
infowindow.open(map, marker);
});
}

Categories

Resources