This is my geocoder google map code
MY code work when i change the select option
the marker is add in map, when i select multiple places,
i want to remove previous marker.
<!DOCTYPE html>
<html><head><meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8"><title>Geocoding service</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&sensor=false"></script>
<script>
var geocoder;var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(9.9252007,78.1197754);
var mapOptions = {
zoom: 8,center: latlng
} map = new google.maps.Map(document.getElementById('map-canvas'), 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>
</head><body>
<div align="center" verticle-align="ce">
<form method="get" action="">
<select name="address" id="address" onChange="codeAddress()" >
<option value="chennai,india">chennai,india</option>
<option value="madurai,india">madurai,india</option>
<option value="bangalore,india">bangalore,india</option>
<option value="delhi,india">Delhi</option>
</select>
</form> </div>
<div id="map-canvas" style="width:750px;height:500px;"></div>
</body></html>
working of the code:
when i load the page ,it automatic load the initial place, i change the option value it will load the choose one.
Make marker as global variable, move marker definition to initialize() function and on change of selection set position using marker.setPosition():
var geocoder;
var map;
var marker;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(9.9252007,78.1197754);
var mapOptions = {
zoom: 8,
center: latlng
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
marker = new google.maps.Marker({
map: map
});
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var position = results[0].geometry.location;
map.setCenter(position);
marker.setPosition(position);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
See example at jsbin.
Related
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>
Can anybody help me with a Google API which get me all surrounding information based on Pincode as an input.
Basically, if I input Pincode number then API should return all shopping malls, bridges, hospitals, hotels etc. I want to be able to store these information in database.
Please share your thoughts.
I hope following code will help you. What it does? 1. Take your pincode from input field, geocode it. 2. From the result of geocode, it applies on places api to find nearby stores in 500 meter radius.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Geocoding service</title>
<style>
html, body, #map-canvas {
height: 800px;
widows: 700px;
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&signed_in=true&libraries=places"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), 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
});
var request = {
location: results[0].geometry.location,
radius: '500',
types: ['store']
}; //500 meters and stores only
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}});}
function callback(results, status) {
console.log(status, results);
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
//createMarker(results[i]);
var marker = new google.maps.Marker({
map:map,
position: place.geometry.location
})
}}}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<input id="address" type="textbox" value="452009">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas"></div></body></html>
If you have any more queries, please comment, we can work on it.
Regards,
Suyash
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>
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
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,
})