pass data from vb to aspx with googlemaps api - asp.net

i need to show some marker on googlemaps.
I have write this section and i pass the data with locationList array, but the map don't show all my markers. Can you help me for understand where i have the problem?
Thank's for answers.
<asp:Content id="CustomScripts" ContentPlaceHolderID="CustomScript" runat ="server">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
function initialize() {
var mapCanvas = document.getElementById('map-canvas');
var mapOptions = {
center: new google.maps.LatLng(44.837367, 11.029718),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapCanvas, mapOptions);
var temp = locationList
for (var i = 0; i < locationList.length; i++) {
var args = locationList[i].split(",");
var location = new google.maps.LatLng(args[0], args[1])
var marker = new google.maps.Marker({
position: location,
map: map
});
var j = i + 1;
marker.setTitle(message[i].replace(/(<([^>]+)>)/ig, ""));
attachSecretMessage(marker, i);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
function attachSecretMessage(marker, number) {
var infowindow = new google.maps.InfoWindow({
content: message[number],
size: new google.maps.Size(50, 50)
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
$(document).ready(function () {
$("#MainContent_time1 , #MainContent_time2").datetimepicker({
dateFormat: 'yy/mm/dd',
timeFormat: 'HH:mm:ss',
pick12HourFormat: false
});
$("#MainContent_time1 , #MainContent_time2").keydown(function (e) {
var charCode = e.which;
if (charCode != 8 && charCode != 46) {
e.preventDefault();
} else {
var id = $(this).attr("id");
$("#" + id).val("");
}
});
});
</script>

Related

Issue in infowindow content pagination using google API's datatable

I am new to google map. I need an help to implement pagination for the table content inside infowindow while clicking marker.
Here is my code :
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages': ['table']});
var map;
var myCenter=new google.maps.LatLng(51.508742,-0.120850);
var mapInfos = [];
var infoWindowView = new google.maps.InfoWindow;
function initialize()
{
map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom:5,
center: new google.maps.LatLng(49.072086992455475,-5.05078125),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker=new google.maps.Marker({
position: myCenter
});
marker.setMap(map);
function mapInfoTable(container)
{
this.tableContainer = container;
var me = this;
var cssClass = {rowNumberCell: 'rowNumberCellClass'};
this.dT = new google.visualization.DataTable();
this.dT.addColumn("string", "Name");
this.dT.addColumn("string", "City");
this.populateTable = function()
{
this.dT.addRows([
['A1' ,'C1'],
['A2' ,'C2'],
['A3' ,'C3'],
['A4' ,'C4'],
['A5' ,'C5'],
['A6' ,'C6'],
['A7' ,'C7'],
['A8' ,'C8']
]);
this.draw();
}
this.table = new google.visualization.Table(document.getElementById(this.tableContainer));
this.draw = function()
{
this.table.draw(this.dT, {allowHtml: true, showRowNumber: true, cssClassNames: cssClass, page: 'enable', pageSize : 4, pagingSymbols: {prev: 'Previous',next: 'Next'}});
}
}
google.maps.event.addListener(marker, 'click', function(e) {
var InfoTab = new mapInfoTable('TableInfo');
InfoTab.populateTable(mapInfos);
var content = document.getElementById("TableInfo").innerHTML;
infoWindowView.setContent(content);
infoWindowView.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="mapCanvas" style="width:800px;height:500px"></div>
<div id="TableInfo" style="position:fixed;"></div>
</body>
</html>
Please let me know where the problem lies.
You need to wait for the 'domready' event on the infowindow before populating the table.
proof of concept fiddle
code snippet:
google.load('visualization', '1', {
'packages': ['table']
});
var map;
var myCenter = new google.maps.LatLng(51.508742, -0.120850);
var mapInfos = [];
var infoWindowView = new google.maps.InfoWindow;
function initialize() {
map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 5,
center: new google.maps.LatLng(49.072086992455475, -5.05078125),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: myCenter
});
marker.setMap(map);
function mapInfoTable(container) {
this.tableContainer = container;
var me = this;
var cssClass = {
rowNumberCell: 'rowNumberCellClass'
};
this.dT = new google.visualization.DataTable();
this.dT.addColumn("string", "Name");
this.dT.addColumn("string", "City");
this.populateTable = function() {
this.dT.addRows([
['A1', 'C1'],
['A2', 'C2'],
['A3', 'C3'],
['A4', 'C4'],
['A5', 'C5'],
['A6', 'C6'],
['A7', 'C7'],
['A8', 'C8']
]);
this.draw();
}
this.table = new google.visualization.Table(document.getElementById(this.tableContainer));
this.draw = function() {
this.table.draw(this.dT, {
allowHtml: true,
showRowNumber: true,
cssClassNames: cssClass,
page: 'enable',
pageSize: 4,
pagingSymbols: {
prev: 'Previous',
next: 'Next'
}
});
}
}
google.maps.event.addListener(marker, 'click', function(e) {
var dTableInfo = document.createElement("div");
dTableInfo.id = "dTableInfo";
google.maps.event.addListener(infoWindowView, 'domready', function() {
var InfoTab = new mapInfoTable('dTableInfo');
InfoTab.populateTable(mapInfos);
});
infoWindowView.setContent(dTableInfo);
infoWindowView.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#mapCanvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://www.google.com/jsapi"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="mapCanvas"></div>

Implementing google place autocomplete

This is my code for places autocomplete and search.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places">
</script>
<script>
var geocoder;
var map;
function initialize() {
var input = document.getElementById('address');
var options = {
componentRestrictions: {country: "in"}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(18.52043030000, 73.85674369999);
var mapOptions = {
zoom: 15,
//center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
This is my html code.
<input id="address" type="textbox" size="30">
<input type="button" value="Search" onclick="codeAddress()">
It is working fine but I dont want to user to click the button. When suggestions appeared, and when user select any of suggestion options, map will have to navigate to that place. How do I do this???
When User select any option from dropdown, map should navigate to that place.
Take a look at this example and the implementation of the place_changed event.
var place = autocomplete.getPlace();
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
}
This way you can pan the map to the location of the autocomplete result.
This is my working code..
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places">
</script>
<script>
var geocoder;
var map;
function initialize() {
var input = document.getElementById('address');
var options = {
componentRestrictions: {country: "in"}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(18.52043030000, 73.85674369999);
var mapOptions = {
zoom: 15,
//center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.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(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Now user can select option from dropdown and map will navigate to that place. And also on search button click.
Hope this might help you
function initialize(){
var mapOptions = {//Map Properties
zoom:12,
center: Bangalore
};
googleMap = new google.maps.Map(document.getElementById('map-holder'),mapOptions);//map-holder is a div which holds map in my html
var defaultBounds = new google.maps.LatLngBounds(//bounds for Bengaluru
new google.maps.LatLng(12.7342888,77.3791981),
new google.maps.LatLng(13.173706,77.8826809)
);
googleMap.fitBounds(defaultBounds);
var input = (document.getElementById('searchInput'));//search input element
googleMap.controls[google.maps.ControlPosition.TOP_LEFT].push(input);//binding it to map
var searchBox = new google.maps.places.SearchBox((input));
google.maps.event.addListener(searchBox, 'places_changed', function() {//triggers when search is performed
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
bounds.extend(place.geometry.location);
//googleMap.fitBounds(place.geometry.viewport);
}
googleMap.fitBounds(bounds);
});
google.maps.event.addListener(googleMap, 'bounds_changed', function() {
var bounds = googleMap.getBounds();
searchBox.setBounds(bounds);
})
}

google map api masterpage coordinate

it's working but when I want to use these code in masterpage I have a problem.
this Problem is about coordinates.
it's looking work but don't take me a coordinates.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.1&sensor=false&language=tr"></script>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<link href="css/yonetici.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function (responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var latLng = new google.maps.LatLng(39.909450, 34.849715);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function () {
updateMarkerAddress('Sürükleniyor...');
});
document.forms[0].txtLat.value = 40.775146501143766;
document.forms[0].txtLng.value = 30.384921661376946;
google.maps.event.addListener(marker, "drag", function () {
var latlng = marker.getPosition();
document.forms[0].txtLat.value = latlng.lat();
document.forms[0].txtLng.value = latlng.lng();
});
google.maps.event.addListener(marker, 'dragend', function () {
geocodePosition(marker.getPosition());
});
}
// Onload handler to fire off the app.
</script>
<script type="text/javascript">
$(function () {
var menu_ul = $('.menu > li > ul'),
menu_a = $('.menu > li > a');
menu_ul.hide();
menu_a.click(function (e) {
e.preventDefault();
if (!$(this).hasClass('active')) {
menu_a.removeClass('active');
menu_ul.filter(':visible').slideUp('normal');
$(this).addClass('active').next().stop(true, true).slideDown('normal');
} else {
$(this).removeClass('active');
$(this).next().stop(true, true).slideUp('normal');
}
});
});
</script>
</head>
<body onload="initialize()">
<form id="form1" runat="server">
<div class="ad_googlemaps_area" >
<div id="mapCanvas"></div>
<div id="infoPanel">
<div id="info" style="display:none;" ></div>
<b>Tahmini Adres:</b>
<div id="address" ></div>
<b>Enlem</b>
<asp:TextBox ID="txtLat" runat="server"></asp:TextBox>
<b>Boylam:</b>
<asp:TextBox ID="txtLng" runat="server"></asp:TextBox>
</div>
</div>
</form>
</body>
remove the onload attribute and initialize method from your body element and javascript both instead put your code inside the pageLoad method as below:
function pageLoad(sender, args) { //use this method to load your map
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(39.909450, 34.849715);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function () {
updateMarkerAddress('Sürükleniyor...');
});
document.forms[0].txtLat.value = 40.775146501143766;
document.forms[0].txtLng.value = 30.384921661376946;
google.maps.event.addListener(marker, "drag", function () {
var latlng = marker.getPosition();
document.forms[0].txtLat.value = latlng.lat();
document.forms[0].txtLng.value = latlng.lng();
});
google.maps.event.addListener(marker, 'dragend', function () {
geocodePosition(marker.getPosition());
});
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function (responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
// Onload handler to fire off the app.
}
Let me know if you still have trouble to load your map.
I try but same problem.
function pageLoad(sender, args) { //use this method to load your map
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(39.909450, 34.849715);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function () {
updateMarkerAddre**strong text**ss('Sürükleniyor...');
});
no problems so far
problem Start in here
document.forms[0].txtLat.value = 40.775146501143766;
document.forms[0].txtLng.value = 30.384921661376946;
google.maps.event.addListener(marker, "drag", function () {
var latlng = marker.getPosition();
document.forms[0].txtLat.value = latlng.lat();
document.forms[0].txtLng.value = latlng.lng();
});
google.maps.event.addListener(marker, 'dragend', function () {
geocodePosition(marker.getPosition());
});
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function (responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
// Onload handler to fire off the app.
}

i get undefined at marker properties

i user markerclustererplus and i want to show info window on cluster click. but i get undefined for all marker in a cluster. i just can't figure it out why and what can be happened. here is my code
<!DOCTYPE html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>PHP/MySQL & Google Maps Example</title>
<style type="text/css">
html, body, #map { margin: 0; padding: 0; height: 95% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn-history/r315/trunk/markerwithlabel/src/markerwithlabel_packed.js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var oncekimarker=null;
var customIcons = {
satilik: {
icon: 'images/pins/yellow.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
kiralik: {
icon: 'images/pins/blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function initialize() {
var markers = null;
var mcmarkers = [];
var globalMarker = [];
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(39, 35),
zoom: 6,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
var infowindow = new google.maps.InfoWindow();
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"))
var point = new google.maps.LatLng(lat, lng);
var html = "something";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
mcmarkers.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
}
var mcOptions = {
gridSize: 30,
maxZoom: 13,
zoomOnClick: false,
averageCenter: true
};
var mc = new MarkerClusterer(map, mcmarkers, mcOptions);
google.maps.event.addListener(mc, 'clusterclick', function(cluster) {
var content = '';
// Convert lat/long from cluster object to a usable MVCObject
var info = new google.maps.MVCObject;
info.set('position', cluster.center_);
//Get markers
var yazmarkers = cluster.getMarkers();
var titles = "";
//Get all the titles
for(var i = 0; i < yazmarkers.length; i++) {
titles += yazmarkers[i].name + "\n";
}
infowindow.close();
infowindow.setContent(titles); //set infowindow content to titles
infowindow.open(map, info);
google.maps.event.addListener(map, 'zoom_changed', function() { infowindow.close() });
});
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
//infoWindow.open(map, marker);
if (oncekimarker) oncekimarker.setAnimation(null);
marker.setAnimation(google.maps.Animation.BOUNCE);
oncekimarker = marker;
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
</div>
<div id="map" style="width: 80%"></div>
</body>
</html>
any help whoul be appreciated. thanks for all your helps.
Your markers do not have a "name" property.
titles += yazmarkers[i].name + "\n";
You can add one by creating them like this
var marker = new google.maps.Marker({
name: name,
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
Warning: While this works with the API at present, it is not documented behavior, you may want to use the "title" property instead, which is documented and has the benefit of appearing on the Marker as a tooltip on mouseover.
working example

close InfoWindow before open another

I have a problem with InfoWindow. I have an ajax function that retrieves data via JSON, but I can not get close InfoWindow automatically when you open another.
My code is this:
var mapOptions = {
center: new google.maps.LatLng(44.49423583832911, 11.346244544982937),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mappa_locali"),mapOptions);
$.ajax({
type:'GET',
url:"locali_json.php"+urlz,
success:function(data){
var json = JSON.parse(data);
for (var i=0; i<json.length; i++) {
point = new google.maps.LatLng(json[i].latitudine,json[i].longitudine);
var infowindow = new google.maps.InfoWindow;
infowindow.setContent(''+json[i].nome_locale+'<br>'+json[i].address);
addMarkerz(point,infowindow);
}
}
})
}
function addMarkerz(point,infowindow) {
position: point,
map: map
});
google.maps.event.addListener(marker,'mouseover',infoCallback(infowindow, marker));
markers.push(marker);
infos.push(infowindow);
}
function infoCallback(infowindow, marker) {
return function() {
infowindow.close();
infowindow.open(map, marker);
};
}
Does anyone know where decreased mistake? Or do you have any advice for me?
The suggestion is only create one infowindow (in the global scope), reuse it and change its contents when a marker is clicked, close it if the user clicks on the map.
code snippet (removes the dependency on the AJAX call):
// global variables
var map;
var markers = [];
var infowindow = new google.maps.InfoWindow();
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(44.49423583832911, 11.346244544982937),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mappa_locali"), mapOptions);
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
point = new google.maps.LatLng(json[i].latitudine, json[i].longitudine);
var infowindowHtml = '' + json[i].nome_locale + '<br>' + json[i].address;
addMarkerz(point, infowindowHtml);
}
}
function addMarkerz(point, infowindowHtml) {
var marker = new google.maps.Marker({
position: point,
map: map
});
google.maps.event.addListener(marker, 'mouseover', infoCallback(infowindowHtml, marker));
markers.push(marker);
}
function infoCallback(infowindowHtml, marker) {
return function() {
infowindow.close();
// update the content of the infowindow before opening it
infowindow.setContent(infowindowHtml)
infowindow.open(map, marker);
};
}
var data = JSON.stringify([{
latitudine: 44.494887,
longitudine: 11.3426163,
id_locale: "0",
nome_locale: "Bologna",
address: "Bologna, Italy"
}, {
latitudine: 44.4946615,
longitudine: 11.314634999999953,
id_locale: "0",
nome_locale: "Quartiere Saragozza",
address: "Quartiere Saragozza, Bologna, Italy"
}]);
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#mappa_locali {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="mappa_locali"></div>
function infoCallback(infowindow, marker) {
return function() {
infowindow.close();
infowindow.open(map, marker);
};
}
should be changed to
function infoCallback(infowindow, marker) {
return function() {
//Close active window if exists
if (activeWindow != null) {
activeWindow.close();
}
//Open new window
infowindow.open(map,marker);
//Store new window in global variable
activeWindow = infowindow;
};
}
and declare activeWindow as a global variable in your .js file as var activeWindow.
I think I have a simple solution. I just save the last open mark. On the next click first of all I close the last mark.
var markers = [];
var infowindows = [];
function addMarkes(facilityID) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < variants.length; i++) {
var v = variants[i];
var position = new google.maps.LatLng(v.Lat, v.Long);
bounds.extend(position);
markers[i] = new google.maps.Marker({
position: position,
title: v.Title,
map: map,
animation: google.maps.Animation.DROP,
icon: v.Icon,
infoWindowIndex: i //synchronize with infoWindows
});
var localContent = '<div><span class="address">' + v.Address + '</span></div>';
infowindows[i] = new google.maps.InfoWindow({
content: localContent
});
//Just for multiple marks.
if (variants.length > 0) {
var lastOpen = -1; //Save the last open mark
google.maps.event.addListener(markers[i], 'click', function (innerKey) {
return function () {
//Close the last mark.
if (lastOpen > -1) {
infowindows[lastOpen].close();
}
infowindows[innerKey].open(map, markers[innerKey]);
lastOpen = innerKey;
}
}(i));
}
}
map.fitBounds(bounds);
}

Resources