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

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>

Related

toggle kml in google maps api

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>

autocomplete the data for Reverse Geocoding without manual input

this is the Reverse Geocoding from google api maps.My question is..
It is possible to remove Or HIDE the <div id="panel"> and get the data from current user location,without user need to press the button to Reverse Geocoding?
I want only to show the address of the user and NO the altitude & longitude..
thank you
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Reverse Geocoding</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var geocoder;
var map;
var infowindow = new google.maps.InfoWindow();
var marker;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: 'roadmap'
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeLatLng() {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
width: 350px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
#latlng {
width: 225px;
}
</style>
</head>
<body>
<div id="panel">
<input id="latlng" type="text" value="40.714224,-73.961452">
<input type="button" value="Reverse Geocode" onclick="codeLatLng()">
</div>
<div id="map-canvas"></div>
</body>
</html>
Yes you can.
I hope you're aware of HTML5 Geolocation, which will help you to get the current position of user.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
revereGeoCode(position.coords.latitude, position.coords.longitude);
});
} else {
// make sure to handle the failure
}
Using this apply you concept and get rid of the manually obtaining the lat and lng.
Complete code will be like below
var geocoder;
var map;
var marker;
var infowindow = new google.maps.InfoWindow();
function initializeMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
revereGeoCode(position.coords.latitude, position.coords.longitude);
});
} else {
console.log("er")
// make sure to handle the failure
}
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(40.730885, -73.997383),
mapTypeId: 'roadmap'
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function revereGeoCode(lat, lng) {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
// place your marker coding
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initializeMap);
JSFiddle

Street View Using google api

Hello i m using Google API v 3.0 for showing street view,but street view is not showing for a prticular point but maps.google.com is showing street view for this location. where i m wrong.
My code is below :-
<!DOCTYPE html>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<html>
<head>
<meta charset="utf-8">
<title>Street View service</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var latitude=null;
var longitude=null;
var fenway;
var map;
var panoramaOptions;
function initialize() {
var value = '950 COUNTRY CLUB DRIVE, MORAGA 94556 ';
alert("value"+value);
var infoWindow = new google.maps.InfoWindow;
$.ajax({
url:"http://maps.googleapis.com/maps/api/geocode/json?address="+value+"&sensor=false",
type: "POST",
success:function(res){
latitude=res.results[0].geometry.location.lat;
alert("latitude"+latitude);
longitude=res.results[0].geometry.location.lng;
alert("longitude"+longitude);
}
});
fenway = new google.maps.LatLng(latitude,longitude);
var mapOptions = {
center: fenway,
zoom: 14
};
var map = new google.maps.Map(
document.getElementById('map-canvas'), mapOptions);
var panoramaOptions = {
position: fenway,
pov: {
heading: 34,
pitch: 10
}
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'),panoramaOptions);
map.setStreetView(panorama);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="width: 400px; height: 300px"></div>
<div id="pano" style="position:absolute; left:410px; top: 8px; width: 400px; height: 300px;"></div>
</body>
</html>
For the street view you can refer to this API https://developers.google.com/maps/documentation/streetview/
Here you can change FOV, pitch heading. Hope this helps

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-->