I want to create dynamic Google map based on Autocomplete Input. I have written the code as:-
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDeAtURNzEX26_mLTUlFXYEWW11ZdlYECM&libraries=places&language=en"></script>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
var map_options = {
center: {
lat: 19.0825223,
lng: 72.7411155
},
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('sale_map_canvas'),map_options);
var marker = new google.maps.Marker({
position:{
lat: 19.0825223,
lng: 72.7411155
},
map:map,
draggable:true
});
var city_options = {
types: ['(cities)'],
componentRestrictions: {country: "in"}
}
var locality_options = {
componentRestrictions: {country:"in"}
}
var city = new google.maps.places.Autocomplete(document.getElementById('sale_city'),city_options);
var locality = new google.maps.places.Autocomplete(document.getElementById('sale_locality'),locality_options);
google.maps.event.addListener(city,'place_changed',function(){
var places = city.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i,place;
for (i = 0; place=places[i]; i++)
{
console.log(place.geometry,location);
bounds.extend(place.geometry.location);
marker.setPosition(place.geometry.location);
}
map.fitBounds(bounds);
map.setZoom(15);
});
google.maps.event.addListener(locality,'place_changed',function(){
var places = locality.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i,place;
for (i = 0; place=places[i]; i++)
{
console.log(place.geometry.location);
bounds.extend(place.geometry.location);
marker.setPosition(place.geometry.location);
}
map.fitBounds(bounds);
map.setZoom(15);
});
</script>
<body>
<input id="sale_city" name="sale_city" type="text" class="validate" autocomplete="on" placeholder="" required>
<label for="sale_city">City</label>
<input id="sale_locality" name="sale_locality" type="text" class="validate" autocomplete="on" placeholder="" required>
<label for="sale_locality">Locality</label>
<div id="sale_map_canvas"></div>
</body>
The Map isn't showing up. Please Solve it..I've written the code by referring the video on https://youtu.be/2n_r0NDekgc
There are few issues in the code.
Map div "sale_map_canvas" is missing.
Map should be loaded on page load.
I have changed the code and now map is loading
<style>
#sale_map_canvas {
height: 100%;
}
</style>
<script src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
var map;
function initialize() {
var map_options = {
center: {
lat: 19.0825223,
lng: 72.7411155
},
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('sale_map_canvas'),map_options);
var marker = new google.maps.Marker({
position:{
lat: 19.0825223,
lng: 72.7411155
},
map:map,
draggable:true
});
var city_options = {
types: ['(cities)'],
componentRestrictions: {country: "in"}
}
var locality_options = {
componentRestrictions: {country:"in"}
}
var city = new google.maps.places.Autocomplete(document.getElementById('sale_city'),city_options);
var locality = new google.maps.places.Autocomplete(document.getElementById('sale_locality'),locality_options);
google.maps.event.addListener(city,'place_changed',function(){
var place = city.getPlace();
var bounds = new google.maps.LatLngBounds();
console.log(place.geometry,location);
bounds.extend(place.geometry.location);
marker.setPosition(place.geometry.location);
map.fitBounds(bounds);
map.setZoom(15);
});
google.maps.event.addListener(locality,'place_changed',function(){
var place = locality.getPlace();
var bounds = new google.maps.LatLngBounds();
console.log(place.geometry.location);
bounds.extend(place.geometry.location);
marker.setPosition(place.geometry.location);
map.fitBounds(bounds);
map.setZoom(15);
});
};
google.maps.event.addDomListener(window, "load", initialize);
</script>
<body>
<input id="sale_city" name="sale_city" type="text" class="validate" autocomplete="on" placeholder="" required>
<label for="sale_city">City</label>
<input id="sale_locality" name="sale_locality" type="text" class="validate" autocomplete="on" placeholder="" required>
<label for="sale_locality">Locality</label>
<div id="sale_map_canvas"></div>
</body>
Related
I have the following code and I want to set and change the circle's radius through user's input using input box and button. Any help will be appreciated. EDIT. This is the revised code based on the example provided below but still won't work for me. Every help will be appreciated.
<apex:page controller="GeoLocatorController" sidebar="false" showheader="false">
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { width:100%;height:80%; }
.controls
</style>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBJkHXEVXBSLY7ExRcxoDxXzRYLJHg7qfI"></script>
<script>
var circle;
function initialize() {
//Setting default center of the system
var mapCenter = {
center: new google.maps.LatLng(36.2048, 138.2529),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), mapCenter);
//Get User's Geolocation and Set as the Center of the System
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
userLat = position.coords.latitude;
userLng = position.coords.longitude;
userLoc = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(userLoc);
//User Marker's Image
var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
//Create Marker for the User's Location
var centerLoc = new google.maps.Marker({
position : new google.maps.LatLng(userLat, userLng),
map : map,
icon: image,
title : 'Your Position!',
draggable : true,
animation: google.maps.Animation.DROP
});
//Create Circle and Bind it to User's Location
circle = new google.maps.Circle({
map: map,
radius: 100, // 10 miles in metres
fillColor: '#AA0000'
});
circle.bindTo('center', centerLoc, 'position');
marker.setMap(map);
});
function updateRadius(){
var rad = document.getElementById("value_rad").value;
circle.setRadius(parseFloat(rad));
}
}
loadHotels();
}
//Load Records from Cloud
function loadHotels({Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.GeoLocatorController.findAll}',
function(result, event){
if (event.status) {
for (var i=0; i<result.length; i++) {
var id = result[i].Id;
var name = result[i].Name;
var lat = result[i].Location__Latitude__s;
var lng = result[i].Location__Longitude__s;
addMarker(id, name, lat, lng);
}
} else {
alert(event.message);
}
},
{escape: true}
);
}
//Create Markers for the Records from the Cloud
function addMarker(id, name, lat, lng) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
title: name,
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
console.log()
</script>
</head>
<body>
<div id="googleMap" style="width:100%;height:80%;"/>
<input id="value_rad" />
<input id="radius" type="button" value="Search" onclick="updateRadius()"/>
</body>
</apex:page>
See this code (it's work), and adapt your code
var user_lat;
var user_lng;
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
user_lat = crd.latitude;
user_lng = crd.longitude;
};
function error(err) {
alert('ERROR(' + err.code + '): ' + err.message);
};
var circle;
var myCenter;
function initialize() {
navigator.geolocation.getCurrentPosition(success, error, options);
myCenter = new google.maps.LatLng(user_lat, user_lng);
var mapProp = {
center: myCenter,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var marker = new google.maps.Marker({
position: myCenter,
});
circle = new google.maps.Circle({
map: map,
radius: 100, // 10 miles in metres
fillColor: '#AA0000',
center: myCenter
});
marker.setMap(map);
}
function updateRadius(){
var rad = document.getElementById("value_rad").value;
circle.setRadius(parseFloat(rad));
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBJkHXEVXBSLY7ExRcxoDxXzRYLJHg7qfI"></script>
<div id="googleMap" style="width:500px;height:380px;"></div>
<input id=value_rad />
<input id="radius" type="button" value="test" onclick="updateRadius()"/>
When I run my code, the map doesn't display. I am working on my localhost. I want to put lat and lng to inputs. Then when I change the lat and lng the inputs will change dynamically. How can I solve this problem?
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div id="googleMap" style="width:500px;height:500px;"></div>
Lat: <input type="text" id="lat"><br>
Lng: <input type="text" id="lng">
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(41,28);
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("googleMap"), myOptions);
addMarker(myLatlng, 'Default Marker', map);
map.addListener('click',function(event) {
addMarker(event.latLng, 'Click Generated Marker', map);
);
}}
function addMarker(latlng,title,map) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: title,
draggable:true
});
marker.addListener('drag',function(event) {
$('#lat').val() = event.latLng.lat();
$('#lng').val() = event.latLng.lng();
});
marker.addListener('dragend',function(event) {
$('#lat').val() = event.latLng.lat();
$('#lng').val() = event.latLng.lng();
});}
</script>
</body></html>
You have some bugs in your code.. and you are not calling the function
initialize(). Try this updated code
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div id="googleMap" style="width:500px;height:500px;"></div>
Lat: <input type="text" id="lat"><br>
Lng: <input type="text" id="lng">
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(41,28);
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("googleMap"), myOptions);
addMarker(myLatlng, 'Default Marker', map);
map.addListener('click',function(event) {
addMarker(event.latLng, 'Click Generated Marker', map);
});
}
function addMarker(latlng,title,map) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: title,
draggable:true
});
marker.addListener('drag',function(event) {
$('#lat').val(event.latLng.lat()) ;
$('#lng').val(event.latLng.lng()) ;
});
marker.addListener('dragend',function(event) {
$('#lat').val(event.latLng.lat()) ;
$('#lng').val(event.latLng.lng()) ;
});
}
initialize();
</script>
</body></html>
Here I can save selected coordinates. İt may help someone.
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div id="googleMap" style="width:500px;height:500px;"></div>
Lat: <input type="text" id="lat"><br>
Lng: <input type="text" id="lng">
<p id="results">result</p>
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(41.015137,28.979530);
var myOptions = {
zoom: 10,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("googleMap"), myOptions);
addMarker(myLatlng, 'Default Marker', map);
map.addListener('click',function(event) {
addMarker(event.latLng, 'Click Generated Marker', map);
});
}
function addMarker(latlng,title,map) {
var coords = [];
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: title,
draggable:true
});
marker.addListener('drag',function(event) {
$('#lat').val(event.latLng.lat()) ;
$('#lng').val(event.latLng.lng()) ;
});
marker.addListener('dragend',function(event) {
$('#lat').val(event.latLng.lat()) ;
$('#lng').val(event.latLng.lng()) ;
coords.push(event.latLng.lat());
coords.push(event.latLng.lng());
$("#results").append('<div>'+JSON.stringify(coords)+'</div>');
coords = [];
});
}
initialize();
</script>
</body></html>
I have this code of google map with coordinates values
the questions is how we can merge the text field of Lat & Lon into one field only,
so we need one text field only display the coordinated (Lat,Lon)
can any one help
the code is below
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?
sensor=false"></script>
<br />
Copy this number and past it in GPS field
<br />
<br />
<input id="divLon" type="text" />
<input id="divLat" type="text" />
<br />
<br />
<div id="map_canvas" style="width: 600px; height: 600px;"></div>
<script type="text/javascript">
var marker;
function initialize() {
var lat;`enter code here`
var lon;
navigator.geolocation.getCurrentPosition(function (location) {
lat = location.coords.latitude;
lon = location.coords.longitude;
var city = new google.maps.LatLng(lat, lon);
var mapOptions = {
zoom: 15,
center: city,
mapTypeId:
google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById
("map_canvas"), mapOptions);
var image = "icon.png";
marker = new google.maps.Marker({
position: city,
map: map,
draggable: true,
icon: image
});
google.maps.event.addListener(marker, 'position_changed',
function (event) {
update();
});
update();
}, function (positionError) {
alert("getCurrentPosition failed: " + positionError.message);
}, { enableHighAccuracy: true });
};
google.maps.event.addDomListener(window, "load", initialize);
function update() {
var lonlan = marker.getPosition();
var divLon = document.getElementById ("divLon");
var divLat = document.getElementById ("divLat");
divLat.value = lonlan.lat ();
divLon.value = lonlan.lng ();
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDfpx62iYkjhpz0J-
vu4Zz96vtWE2TFzQs&signed_in=true&callback=initMap"></script>
</body>
</html>
Try this code:
function update() {
var lonlan = marker.getPosition();
var divLat = document.getElementById ("divLat");
divLat.value = lonlan.lat ()+", "+lonlan.lng ();
}
Simplest solution, use the .toUrlValue method of a google.maps.LatLng
function update() {
var lonlan = marker.getPosition();
var divLatLon = document.getElementById("divLatLon");
divLatLon.value = lonlan.toUrlValue(6);
}
code snippet:
var marker;
function initialize() {
var lat;
var lon;
navigator.geolocation.getCurrentPosition(function(location) {
lat = location.coords.latitude;
lon = location.coords.longitude;
var city = new google.maps.LatLng(lat, lon);
var mapOptions = {
zoom: 15,
center: city,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById
("map_canvas"), mapOptions);
var image = "icon.png";
marker = new google.maps.Marker({
position: city,
map: map,
draggable: true,
icon: image
});
google.maps.event.addListener(marker, 'position_changed',
function(event) {
update();
});
update();
}, function(positionError) {
alert("getCurrentPosition failed: " + positionError.message);
}, {
enableHighAccuracy: true
});
};
google.maps.event.addDomListener(window, "load", initialize);
function update() {
var lonlan = marker.getPosition();
var divLatLon = document.getElementById("divLatLon");
divLatLon.value = lonlan.toUrlValue(6);
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="divLatLon" />
<div id="map_canvas"></div>
I Have a google map on my site. Users can drag the marker and the map will input the lat and lon into a form for me. See code below. I want to be able to get the address from the lat and lon and put it into my form at "locationbox".
<script src="multi_step_form.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<script type="text/javascript">
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(49.25302534866034,-102.04825518471148);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.HYBRID
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
draggable: true,
position: myLatlng,
map: map,
title: "Your location"
});
google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
});
}
</script>
I have another bit of code to look up the address that I got from https://203luv.wordpress.com/2011/10/21/google-maps-javascript-v3-api-how-to-get-address-from-coordinates-latitude-longitude/ but I just can't figure out how to blend them together.
<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();
var lat = "12.1234";
var long = "98.7654";
var latlng = new google.maps.LatLng(sLat, sLong);
geocoder.geocode({"latLng":latlng},function(data,status){
if(status == google.maps.GeocoderStatus.OK){
var add = data[1].formatted_address; //this is the full address
alert(add);
for(var i=0; i<data[1].address_components.length; i++){
if(results[1].address_components[i].types[0] == "administrative_area_level_1"){
alert(results[1].address_components[i].short_name);
}
}
}
})
My html form looks like this
<div id="map_canvas" style="width: 450px; height: 450px; background-color: Black;"></div>
<div id="latlong">
<p><input size="20" type="text" id="latbox" name="lat" placeholder="Drag the marker on the map or type in the latitude"></p>
<p><input size="20" type="text" id="lngbox" name="lon" placeholder="Drag the marker on the map or type in the longitude"></p>
</div>
<input class="text_field" id="locationbox" name="location" placeholder="Location" type="text" >
Any help would be appreciated
I would suggest calling the reverse geocoder in the dragend event listener function:
google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
var latlng = this.getPosition();
geocoder.geocode({
"latLng": latlng
}, function (data, status) {
if (status == google.maps.GeocoderStatus.OK) {
var add = data[1].formatted_address; //this is the full address
// alert(add);
for (var i = 0; i < data[1].address_components.length; i++) {
if (data[1].address_components[i].types[0] == "administrative_area_level_1") {
document.getElementById('locationbox').value = data[1].address_components[i].short_name;
}
}
}
});
});
proof of concept fiddle
code snippet:
var map;
function initialize() {
var geocoder = new google.maps.Geocoder();
var myLatlng = new google.maps.LatLng(49.25302534866034, -102.04825518471148);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
draggable: true,
position: myLatlng,
map: map,
title: "Your location"
});
google.maps.event.addListener(marker, 'dragend', function(event) {
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
var latlng = this.getPosition();
geocoder.geocode({
"latLng": latlng
}, function(data, status) {
if (status == google.maps.GeocoderStatus.OK) {
var add = data[1].formatted_address; //this is the full address
// alert(add);
for (var i = 0; i < data[1].address_components.length; i++) {
if (data[1].address_components[i].types[0] == "administrative_area_level_1") {
document.getElementById('locationbox').value = data[1].address_components[i].short_name;
}
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" style="width: 450px; height: 450px; background-color: Black;"></div>
<div id="latlong">
<p>
<input size="20" type="text" id="latbox" name="lat" placeholder="Drag the marker on the map or type in the latitude">
</p>
<p>
<input size="20" type="text" id="lngbox" name="lon" placeholder="Drag the marker on the map or type in the longitude">
</p>
</div>
<input class="text_field" id="locationbox" name="location" placeholder="Location" type="text">
I'm trying to add a marker using a button in Google Maps and I'm getting the error, cannot read property lat of null. I'm not that good in Javascript, any help?
function setmarker(){
setLatLng = new google.maps.LatLng(document.getElementById('latitude').value,document.getElementById('longitude').value);
alert(setLatLng);
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var mapOptions = {
zoom: 8,
//center: new google.maps.LatLng(-1.2921897,36.8288574)
};
var marker = new google.maps.Marker({
position: setLatLng,
map: map,
title: 'Obtained coordinate'
});
}
</script>
</head>
<body>
<div id="map-canvas"></div>
<div class="side-panel">
<div>Latitude:<br><input type="text" name="latitude" id="latitude" ></div>
<div>Longitude:<br><input type="text" name="longitude" id="longitude"></div><br>
<!-- <input type="submit" onsubmit="setmarker();"> -->
<button onclick="setmarker()">Show Marker</button>
</div>
When you do document.getElementById('latitude').value that returns the value as a string e.g. "51.23546" instead of the floating point number that Google's API expects.
To make sure they get passed to Google as floats, try:
setLatLng = new google.maps.LatLng(
parseFloat(document.getElementById('latitude').value),
parseFloat(document.getElementById('longitude').value)
);
Thanks for all the answers, stumbled upon the answer in the name of Reverse GeoCoding Service from Google that exactly did what I wanted to quite easily and in the exact way.
From the API: https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
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);