toggle kml in google maps api - google-maps

I am developing a map with a single KML layer. But once it's embedded on a website, I need the user to be able to toggle the KML on and off. I have tried to use suggested code from other questions to make this work, but I'm not having any luck. I'd really appreciate anyone's help in finding a solution to this.
Here is my code. You'll notice that I also have a draggable marker, which when it's moved, changes the GPS co-ordinates at the bottom of the map:
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<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(-23.742023, 29.462218);
var markerPosition = new google.maps.LatLng(-23.460136, 31.3189074);
var 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 kmlLayer = new google.maps.KmlLayer();
var kmlUrl = 'https://dl.dropboxusercontent.com/u/29079095/Limpopo_Hunting_Zones/Zones_2015.kml';
var kmlOptions = {
suppressInfoWindows: false,
preserveViewport: true,
map: map
};
var kmlLayer = new google.maps.KmlLayer(kmlUrl, kmlOptions);
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<style>
#mapCanvas {
width: 1000px;
height: 500px;
float: top;
}
#infoPanel {
float: top;
margin-left: 10px;
}
#infoPanel div {
margin-bottom: 5px;
}
</style>
<div id="mapCanvas"></div>
<div id="infoPanel">
<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>
</div>
</body>
</html>

You need the map to be global to use it inside functions run by click listeners.
Working code snippet, based of the answer to this question:
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></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 kmlUrl = 'https://dl.dropboxusercontent.com/u/29079095/Limpopo_Hunting_Zones/Zones_2015.kml';
var kmlOptions = {
suppressInfoWindows: false,
preserveViewport: true,
map: map
};
var kmlLayer = new google.maps.KmlLayer(kmlUrl, kmlOptions);
*/
}
// 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>
Layer1 <input type="checkbox" id="layer_01" 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>
</div>
</body>
</html>

Related

How do I stop the Google Maps API from automatically refreshing?

Current behaviour: The page constantly refreshes my location and the entire map.
Desired behaviour: I only want to find and display the current location once, not continuously.
How can I achieve this?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>whereami</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript" src="cordova.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key= xyz " type="text/javascript"></script>
<script type="text/javascript">
function onSuccess(position) {
var lat=position.coords.latitude;
var lang=position.coords.longitude;
var myLatlng = new google.maps.LatLng(lat,lang);
var mapOptions = {zoom: 17,center: myLatlng}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({position: myLatlng,map: map});
}
function onError(error) {}
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 0 });
google.maps.event.addDomListener(window, 'load', onSuccess);
</script>
</head>
<body>
<div id="geolocation"></div>
<div id="map-canvas"></div>
</body>
</html>
Don't keep recreating the map. Create the map once (in an "initMap" function), center the map an place the marker in the watchPosition callback function.
jsfiddle
// global variables
var map, marker, polyline;
function initMap() {
// initialize the global map variable
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {
lat: 0,
lng: 0
},
zoom: 1
});
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, {
timeout: 5000
});
}
google.maps.event.addDomListener(window, 'load', initMap);
function onSuccess(position) {
var lat = position.coords.latitude;
var lang = position.coords.longitude;
var myLatlng = new google.maps.LatLng(lat, lang);
map.setCenter(myLatlng);
map.setZoom(18);
if (marker && marker.setPosition)
marker.setMap(myLatlng); // move the marker
else // create a marker
marker = new google.maps.Marker({
position: myLatlng,
map: map
});
}
function onError(error) {
console.log('ERROR(' + error.code + '): ' + error.message);
}
html {
height: 100%;
width: 100%;
}
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0
}
#map-canvas {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="geolocation"></div>
<div id="map-canvas"></div>

Some questions about google maps

Here is my code for a google map
<!DOCTYPE html>
<html>
<head>
<style>
#map_canvas {
width: 900px;
height: 400px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(18.979026,16.468506),
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var icons = {
parking: {
name: 'Parking',
icon: iconBase + 'parking_lot_maps.png'
}
};
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
map: map
});
}
var features = [
{
position: new google.maps.LatLng(-33.91721, 151.22630),
type: 'Parking'
}
var map = new google.maps.Map(map_canvas, map_options)
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>
Why is it wrong?
All what it is supposed to do is be centered and have a marker with the icon parking at a certain lat & long.
I tried following the google tutorial, but I understand it
So any help would be much appreciated
Use MarkerImage to place an custom icon
img = new google.maps.MarkerImage('parking_lot_maps.png');
then
Marker = new google.maps.Marker({
position: pos,
icon: img,
});

How to hide or display a Google Maps Layer?

I have prepared a simplified test case and a screenshot.
I think I'm missing a tiny bit, just few lines of code.
I have 2 overlays (the weather and clouds) in my JavaScript Google Map and would like to hide or show them when a corresponding check box is clicked:
Here is the test case, just paste it into an .html file and it will run:
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
h1,p {
text-align: center;
}
#map {
width: 700px;
height: 400px;
margin-left: auto;
margin-right: auto;
background-color: #CCCCFF;
}
</style>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false&language=de&libraries=weather"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
findCity('Berlin');
$('#weather_box,#clouds_box').click(function(){
alert('How to hide/show layers? Checked: ' + $(this).is(':checked'));
});
});
function createMap(center) {
var opts = {
zoom: 6,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
return new google.maps.Map(document.getElementById('map'), opts);
}
function findCity(city) {
var gc = new google.maps.Geocoder();
gc.geocode({address: city}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var pos = results[0].geometry.location;
var map = createMap(pos);
var marker = new google.maps.Marker({
map: map,
title: city,
position: pos,
animation: google.maps.Animation.DROP
});
var weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.CELSIUS
});
weatherLayer.setMap(map);
//var cloudLayer = new google.maps.weather.CloudLayer();
//cloudLayer.setMap(map);
}
});
}
</script>
</head>
<body>
<h1>Berlin</h1>
<p>Show:
<label><input type="checkbox" id="weather_box" checked>weather</label>
<label><input type="checkbox" id="clouds_box">clouds</label>
</p>
<div id="map"></div>
</body>
</html>
UPDATE: Thanks, here a working version for everyone
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
h1,p {
text-align: center;
}
#map {
width: 700px;
height: 400px;
margin-left: auto;
margin-right: auto;
background-color: #CCCCFF;
}
</style>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false&language=de&libraries=weather"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
var map;
var WeatherLayer;
var CloudsLayer;
$(function() {
findCity('Berlin');
});
function createMap(center) {
var opts = {
zoom: 6,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
return new google.maps.Map(document.getElementById('map'), opts);
}
function findCity(city) {
var gc = new google.maps.Geocoder();
gc.geocode({address: city}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var pos = results[0].geometry.location;
map = createMap(pos);
var marker = new google.maps.Marker({
map: map,
title: city,
position: pos,
animation: google.maps.Animation.DROP
});
weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.CELSIUS
});
weatherLayer.setMap(map);
cloudsLayer = new google.maps.weather.CloudLayer();
//cloudsLayer.setMap(map);
$('#weather_box').click(function(){
weatherLayer.setMap($(this).is(':checked') ? map : null);
});
$('#clouds_box').click(function(){
cloudsLayer.setMap($(this).is(':checked') ? map : null);
});
$('#weather_box,#clouds_box').removeAttr('disabled');
}
});
}
</script>
</head>
<body>
<h1>Berlin</h1>
<p>Show:
<label><input type="checkbox" id="weather_box" disabled="true" checked>weather</label>
<label><input type="checkbox" id="clouds_box" disabled="true">clouds</label>
</p>
<div id="map"></div>
</body>
</html>
You can hide/show the layer with setMap method:
if ($(this).is(':checked'))
weatherLayer.setMap(map); // show
else
weatherLayer.setMap(null); // hide
See working example: http://jsfiddle.net/EeVUr/2/ (removed your second checkbox, as you have only one layer now. But you can easily create two different layers and switch them.)
If you use deckgl along with deckgl, set the visible property to true or false.
and in updateTriggers, keep the variable that decides the visibility
eg:
new GeoJsonLayer({
...otherProps,
updateTriggers: {
visible: [decisionVariable],
}
visible: decisionVariable ? true : false,
})

Drag images on Google Maps wrong position displayed on the map

Here is the JS code. I have two different images that I'm going to place as a marker on the map called DRAGGABLE and DRAGGABLE2.
The map load a kml file.
<script type="text/javascript">
$(document).ready(function() {
$("#draggable").draggable({helper: 'clone',
stop: function(e) {
var point=new google.maps.Point(e.pageX -27,e.pageY -106);
var ll= overlay.getProjection().fromContainerPixelToLatLng(point);
placeMarker(ll, 'alert.png');
}
});
$("#draggable2").draggable({helper: 'clone',
stop: function(e) {
var point=new google.maps.Point(e.pageX - 27,e.pageY -106);
var ll=overlay.getProjection().fromContainerPixelToLatLng(point);
placeMarker(ll, 'facebook.png');
}
});
});
</script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var overlay;
var markers = {};
function initialize() {
var myOptions = {
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var ctaLayer = new google.maps.KmlLayer('test.kml');
ctaLayer.setMap(map);
overlay = new google.maps.OverlayView();
overlay.draw = function() {};
overlay.setMap(map);
}
function placeMarker(location,imgdrag) {
var currentMrkMap;
currentMrkMap = parseInt(document.getElementById('mrkadd').value);
currentMrkMap += 1;
document.getElementById('mrkadd').value = currentMrkMap;
document.getElementById('mrkelements').innerHTML += 'TestCodeHtmlIntoDIV';
var marker = new google.maps.Marker({
id: 'marker_' + currentMrkMap,
position: location,
draggable: true,
map: map,
icon:'img/'+imgdrag
});
id = 'marker_' + currentMrkMap;
markers[id] = marker;
var infowindow = new google.maps.InfoWindow({
content: 'Add element <br><textarea id="txtAr" name="txtAr" rows="5" ></textarea><br>'
});
infowindow.open(map,marker);
google.maps.event.addListener(marker,'click',function() {
var coords = this.getPosition();
var infowindow = new google.maps.InfoWindow({
content: 'Add element <br><textarea id="txtAr" name="txtAr" rows="5" >' + coords +'</textarea><br>'
});
infowindow.open(map,marker);
});
google.maps.event.addListener(marker, "dragend", function() {
var coordinates = document.getElementById("txtAr");
var coords = this.getPosition();
coordinates.value= coords.lat() + ' '+ coords.lng();
});
}
</script>
Css Code. The body and the sidebar are from bootstrap.
<style type="text/css">
body {
padding-top: 60px;
padding-bottom: 60px;
}
.sidebar-nav {
padding: 9px 0;
}
#map_canvas {
width: 100%;
height: 530px;
}
</style>
And HTML code is based on Bootstrap. The portion where I our the map is like this
<div class="span9">
<div class="hero-unit">
<div id="map_canvas"></div>
</div>
</div><!--/span-->

google maps API v3 put draggable maker

this my code,
function initialize() {
if (GBrowserIsCompatible()) {
var city = 'battaramulla';
var center = '';
var map = new GMap2(document.getElementById("map_canvas"));
map.setUIToDefault();
var geocoder = new GClientGeocoder();
geocoder.getLatLng(city, function (point) {
if (!point) {
alert(city+" not found :-(");
} else {
alert(city+" "+point+" found :-)");
map.setCenter(point, 8);
}
});
}
}
I want to add drggable maker to this city(point). Please help me. thanks.
You can try this complete example...
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">`enter code here`
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(-34.397, 150.644);
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('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<style>
#mapCanvas {
width: 500px;
height: 400px;
float: left;
}
#infoPanel {
float: left;
margin-left: 10px;
}
#infoPanel div {
margin-bottom: 5px;
}
</style>
<div id="mapCanvas"></div>
<div id="infoPanel">
<b>Marker status:</b>
<div id="markerStatus"><i>Click and drag the marker.</i></div>
<b>Current position:</b>
<div id="info"></div>
<b>Closest matching address:</b>
<div id="address"></div>
</div>
</body>
</html>
Use geocoder to find the closest address.
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.');
}
});
}