Google Maps: Markers not appearing again after toggle - google-maps

I am a beginner at google maps.
I am trying to toggle google map markers based on there type.
When I unchecked the check-box the marker disappears and upon checking it again the markers do not appears back on the map.
I have tried changing setmap to setvisible in toggleGroup function but that also did not worked .
</style>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Beautiful India</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("parsingxml.php", function(data) {
var xml = data.responseXML;
var 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 point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
html = "<div style=\"position: relative; float: left; width: 225px; height: 80px; border: 0px coral solid;\">" + html + "</div>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
markerGroups[type].push(marker);
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
var markerGroups = { "bar": [], "restaurant": [] };
function toggleGroup(type) {
for (var i = 0; i < markerGroups[type].length; i++) {
var marker = markerGroups[type][i];
if (marker.getMap()==null) {
marker.setVisible(true);
} else {
marker.setVisible(false);
}
}
}
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() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="panel">
<input type="checkbox" id="bar" onclick="toggleGroup('bar')"CHECKED/>
bar
<input type="checkbox" id="bar" onclick="toggleGroup('restaurant')"CHECKED/>
restaurant
</div>
<div id="map" </div>
</body>
</html>

Your issue:
You are mixing 2 different things here: getMap() and getVisible().
How to use:
To render a marker on the map, use:
marker.setMap(map); // where "map" is your map instance
To remove a marker from the map:
marker.setMap(null);
To show a hidden marker:
marker.setVisible(true);
To hide a marker:
marker.setVisible(false);
How to fix:
You should adapt your toggleGroup function accordingly.
Details:
marker.setMap(null);
marker.setVisible(true); // marker will not be shown since it's not on the map anymore

Related

Getting values of cursor from indexedDB

I'm trying to put markers on a google location map API using data I put on an inedexedDB. I'm able to put the markers accurately using the data I get from the DB, but the markers' infowindow doesn't get them accurately.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<style type="text/css">
#map {
width: 700px;
height: 700px;
}
</style>
</head>
<body>
<div id="map"></div>
<button onclick="showMarker()">Show Markers </button>
<script type="text/javascript">
//prefixes of implementation that we want to test
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
//prefixes of window.IDB objects
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.")
}
var db;
var request = window.indexedDB.open("mapDB", 1);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(11.980433, 121.918866),
mapTypeId: google.maps.MapTypeId.HYBRID
});
const locData = [
{ id: "00-01", name: "Boracay", lat: 11.980433, lng: 121.918866 },
{ id: "00-02", name: "Baguio City", lat: 16.402333, lng: 120.596007 },
{ id: "00-03", name: "Isdaan", lat: 15.475479, lng: 120.596349 },
{ id: "00-04", name: "Mount Pinatubo", lat: 15.142973, lng: 120.349302 }
];
request.onerror = function(event) {
console.log("error: ");
};
request.onsuccess = function(event) {
db = request.result;
console.log("success: "+ db);
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("location", {keyPath: "id"});
for (var i in locData) {
objectStore.add(locData[i]);
}
db.onsuccess = function(event) {
showMarker();
};
}
function showMarker() {
var infowindow = new google.maps.InfoWindow();
var marker, i;
var objectStore = db.transaction("location").objectStore("location");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(cursor.value.lat, cursor.value.lng),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(cursor.value.name);
infowindow.open(map, marker);
}
})(marker, i));
cursor.continue();
}
};
}
</script>
</body>
</html>
I have tried searching and reading other sources but I can't seem to find what's the problem. Help is very much appreciated.
This is a duplicate of Google Maps JS API v3 - Simple Multiple Marker Example. You need function closure on the name of the marker.
function showMarker() {
var infowindow = new google.maps.InfoWindow();
var marker;
var objectStore = db.transaction("location").objectStore("location");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(cursor.value.lat, cursor.value.lng),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, name) {
return function() {
infowindow.setContent(name);
infowindow.open(map, marker);
}
})(marker, cursor.value.name));
cursor.continue();
}
};
}
proof of concept fiddle

Search box on Google Maps API

I am trying to put a search box onto my map, but it keeps failing. I have tried to use sample code from a few sites (here: How to add Google Maps Autocomplete search box?; here: How to integrate SearchBox in Google Maps JavaScript API v3?; here: https://developers.google.com/maps/documentation/javascript/examples/places-searchbox; and a tutorial from here: https://www.youtube.com/watch?v=lSdM3yZkj1w). But I can't seem to make it work, and now my map won't even display.
To explain fully, I am trying to make a map that displays a kml (which can be toggled), a marker that can be dragged by the user (which displays co-ordinates where ever the marker is), and a search box to search for an address or co-ordinates (...this is still eluding me).
In the end, I am hoping to move the search box and the kml toggle onto the map, rather than outside.
I'm very new to this, so I apologise in advance for my lack of experience. Any help would be greatly appreciated!
Non-working code below:
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script type="text/javascript">
var map = null;
var geocoder = new google.maps.Geocoder();
var layers=[];
layers[0] = new google.maps.KmlLayer("https://dl.dropboxusercontent.com/u/29079095/Limpopo_Hunting_Zones/Zones_2015.kml",
{preserveViewport: true});
function toggleLayers(i)
{
if(layers[i].getMap()==null){
layers[i].setMap(map);
}
else {
layers[i].setMap(null);
}
}
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(-23.742023, 29.462218);
var markerPosition = new google.maps.LatLng(-23.460136, 31.3189074);
map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 7,
center: latLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var marker = new google.maps.Marker({
position: markerPosition,
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('DRAGGING...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('DRAGGING...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('DRAG & DROP THE MARKER ONTO YOUR DESIRED PROPERTY');
geocodePosition(marker.getPosition());
});
}
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-25.43029134371126, 25.979551931249944),
new google.maps.LatLng(-21.919517708560267, 32.164854665624944));
var options = {
bounds: defaultBounds
};
var input = document.getElementById('pac-input');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(input, options);
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
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)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#mapCanvas {
width: 1000px;
height: 500px;
float: top;
}
#infoPanel {
float: top;
margin-left: 10px;
}
#infoPanel div {
margin-bottom: 5px;
}
</style>
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="SEARCH">
<div id="map-canvas"></div>
CLICK TO DISPLAY ZONES <input type="checkbox" id="CLICK TO HUNTING ZONES" onclick="toggleLayers(0);"/>
<div id="mapCanvas"></div>
<div id="infoPanel">
<div id="address"></div>
<b>MARKER STATUS:</b>
<div id="markerStatus"><i>DRAG & DROP THE MARKER ONTO YOUR DESIRED PROPERTY.</i>
</div>
<b>GPS CO-ORDINATES:</b>
<div id="info"></div>

I want to open maps infowindow from a link on the table

im currenty undataking a project which includes a google map API!im loading markers on the map using mysql from my database. now what am trying to accomplish is something like this i have seen before http://www.tanesco.co.tz/index.php?option=com_wrapper&view=wrapper&Itemid=155
I want to create a link on the displayed table which when clicked it opens up an info window on the map....I completely have no idea where to start
This is my map code
<?php include("connect.php");
?>
<!DOCTYPE html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="stylesheet.css" type="text/css" rel="stylesheet" media="screen" />
<title>AzamTv Customer Database</title>
<style type="text/css">
<!--
.style2 {color: #999999}
.style3 {color: #666666}
.style4 {color: #FF0000}
.style5 {color: #3366FF}
-->
</style>
<script src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script language="javascript" type="text/javascript">
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);
}
//Get element by ID where the function return tand get the latitude and longitude
//do not embed any thing before authorized permition to google.
function load() {
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng( -6.801859, 39.282503),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("mapxml.php", function(data) {
var xml = data.responseXML;
var 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 licence_number = markers[i].getAttribute("Licence_number");
var phone = markers[i].getAttribute("phone");
var business_image = markers[i].getAttribute("business_image");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
//Creating image
var image_src= "<div><img width='100' height='100' src=' "+ business_image +"' /></div>";
var html = "<b>" +"<h4>Business Name:</h4>"+ name + "</b> <br/><br/>"+"<h4>Address:</h4>" + address + "</b> <br/><br/>"+"<h4>Licence Type:</h4>" + licence_number + "</b> <br/><br/>" + "<h4>Phone:</h4>" + phone + "</b> <br/><br/>"+"<h4>Image:</h4>" + image_src + "</br> Zoom out Zoom in" ;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
//If u wanna change the markers by adding custom ones of ur own add here
var customIcons = {
TIN: {
icon: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png'
},
VAT: {
icon: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png'
}
};
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
// Pan map center to marker position
map.panTo(marker.getPosition());
var c= map.getZoom()+3;
var maxZoom=map.mapTypes[map.getMapTypeId()].maxZoom;
if(c<=maxZoom){
map.setZoom(c+3);
}
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function doNothing() {}
function zoomout() {
var d = map.getZoom();
if(d>0){
map.setZoom(d-1);
}
// e = map.getCenter();
// map.setZoom(d - 1);
// map.setCenter(e.Longitude, e.Latitude);
// should be: map.setCenter(e.lat(), e.lng());
}
function zoomin() {
var x = map.getZoom();
var maxZoom=map.mapTypes[map.getMapTypeId()].maxZoom;
if(x<maxZoom){
map.setZoom(x+1);
}
// y = map.getCenter();
// map.setZoom(x + 1);
// map.setCenter(y.Longitude, y.Latitude);
// should be: map.setCenter(y.lat(), y.lng());
}
</script>
<script language="javascript" type="text/javascript">
//Script For The Search
function cleartxt()
{
formsearch.searched1.value="";
}
function settxt()
{
if(formsearch.searched1.value=="")
{
formsearch.searched1.value="Search Customer";
}
}
</script>
</head>
<body onLoad="load()">
<div id="map" style="width: 100%; height: 80%"></div>
</body>
</html>
Thank you all in advance
You create markers like
var marker = new google.maps.Marker({
position: myLatlng,
title:"Your title"
});
create links which on click trigger
infowindow.open(map,marker);
thats all i guess.
EDIT: You could identify which marker needs to be shown by href-parameter

Google API - mapping 500 coordinates

I'm working on a project where I have a need to draw a map with a little over 500 points on it. The code I have works well up to 250 points. But when I have all 500 coordinates in the XML file that it parses, no points end up displaying on the map.
I imagine there is some kind of throttling that is causing it to fail but I can't figure out how to include this in the code.
Any ideas?
locations.xml (abbreviated)
<markers>
<marker name="" address="800 Occidental Ave S Seattle, WA 98134" lat="47.595091" lng="-122.333229" type="location" />
<marker name="" address="Bridge Street, City of Westminster, SW1A 0AA, United Kingdom" lat="51.499100" lng="-0.121955" type="location" />
</markers>
map.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
var customIcons = {
location: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(27.2500, 2.5200),
// world (27.2500, 2.5200), zoom 2
// usa (39.6791686, -95.5335914), zoom 4
zoom: 2,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("locations.xml", function(data) {
var xml = data.responseXML;
var 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 point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
//bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
//infoWindow.setContent(html);
//infoWindow.open(map, 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() {}
</script>
</head>
<body onLoad="load()">
<div id="map" style="width: 1050px; height: 550px"></div>
</body>
</html>
My guess is there is a problem with your data somewhere around the 250th entry.

Markers on Google Maps v3 disappear when I upload to my web server

Very strange. When I preview the file for my map on my local computer, it works just fine and the marker appears. However, when I upload to my web server, the marker disappears. The files are exactly the same...
Does anyone know what's going on?
http://www.andyinman.com/googlemap/test2.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>St. Joseph Larceny Map</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
[ { featureType: "landscape.natural", stylers: [ { hue: "#3bff00" }, { visibility: "off" } ] }]
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(39.7579, -94.8365),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("larceny1.xml", function(data) {
var xml = data.responseXML;
var 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 point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, 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() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map" style="width: 100%; height: 100%"></div>
It works for me in Chrome, Firefox and IE8. Perhaps you have a bad copy of the xml stuck in the browser cache (which browser are you using?)
Try using your own legitimate key. This line
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
should look something more like this
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=AacbdefglcdK7C2GHbQAmdkBID70Uppuf-D030&sensor=true">
</script>
You can apply for your own Google Maps API key on their home page. There are a few reasons why regular users are not allowed to publish using a default Google key because of situations concerning bandwidth, etc. Thus , companies with high volume have to pay to have a license for a Google Maps key, but for your use, a free key will probably work fine.