I'm Using Google Maps API, I have create page where the user search the address and the Marker pops-up on the location its all good but what I really want to do is generate markers when the user clicks anywhere on the map programtically.
JSFiddle
The following adds a click handler to the map, which adds a new marker based on the lat/long.
It then attaches a right-click handler to that marker, which removes it from the map:
google.maps.event.addListener(map, 'click', function(e) {
var marker = new google.maps.Marker({
position: e.latLng,
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(e) {
this.setMap(null);
});
});
function initialize() {
var placeSearch, autocomplete;
var componentForm = {
street_number: 'long_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'long_name',
country: 'long_name',
postal_code: 'long_name'
};
var mapOptions = {
center: new google.maps.LatLng(41.877461, -87.638085),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
disableDefaultUI: true,
streetViewControl: false,
panControl: false
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */
(
document.getElementById('field_autocomplete'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(12); // Why 17? Because it looks good.
}
marker.setIcon( /** #type {google.maps.Icon} */ ({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(25, 34),
scaledSize: new google.maps.Size(50, 50)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''), (place.address_components[1] && place.address_components[1].short_name || ''), (place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div id="infowindow"><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
document.getElementById("field_latitude").value = place.geometry.location.lat();
document.getElementById("field_longitude").value = place.geometry.location.lng();
var formatted_address = place.formatted_address;
document.getElementById("field_formatted_address").value = formatted_address;
//alert(formatted_address);
document.getElementById("field_street_number").value = place.address_components[0].long_name;
//alert(place.address_components[0].long_name);
document.getElementById("field_route").value = place.address_components[1].long_name;
//alert(place.address_components[1].long_name);
document.getElementById("field_locality").value = place.address_components[2].long_name;
//alert(place.address_components[2].long_name);
document.getElementById("field_administrative_area_level_1").value = place.address_components[3].long_name;
//alert(place.address_components[3].long_name);
document.getElementById("field_postal_code").value = place.address_components[4].long_name;
//alert(place.address_components[4].long_name);
document.getElementById("field_country").value = place.address_components[5].long_name;
//alert(place.address_components[5].long_name);
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
google.maps.event.addListener(map, 'click', function(e) {
var marker = new google.maps.Marker({
position: e.latLng,
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(e) {
this.setMap(null);
});
});
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
document.getElementById('field_street_number').value = place.address_components[0].long_name;
document.getElementById('field_route').value = place.address_components[1].long_name;
document.getElementById('field_locality').value = place.address_components[2].long_name;
document.getElementById('field_administrative_area_level_1').value = place.address_components[3].long_name;
document.getElementById('field_postal_code').value = place.address_components[4].long_name;
document.getElementById('field_country').value = place.address_components[5].long_name;
document.getElementById('field_latitude').value = place.geometry.location.lat();
document.getElementById('field_longitude').value = place.geometry.location.lng();
var geolocation = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
document.getElementById('field_latitude').value = latitude;
document.getElementById('field_longitude').value = longitude;
autocomplete.setBounds(new google.maps.LatLngBounds(geolocation, geolocation));
});
}
}
}
initialize();
body {
background: #B04D4F;
}
.frame {
padding-top: 25px;
}
input[type="text"] {
height: 40px;
padding: 5px 10px;
width: 100%;
margin-bottom: 10px;
border: 2px solid #fff;
color: #1c1c1c;
}
label {
color: #fff;
}
#map_canvas {
width: 100%;
height: 300px;
margin: 0px 0;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map_canvas"></div>
<div class="container frame">
<div id="locationField">
<label for="field_autocomplete">Autocomplete Search</label>
<input id="field_autocomplete" name="field_autocomplete" type="text" placeholder="Location Search" onFocus="geolocate()" />
<div class="row">
<div class="col-sm-4">
<label for="field_street_number">Street Number</label>
<input id="field_street_number" type="text" />
</div>
<div class="col-sm-4">
<label for="field_route">Route</label>
<input id="field_route" type="text" />
</div>
<div class="col-sm-4">
<label for="field_locality">City</label>
<input id="field_locality" type="text" />
</div>
</div>
<div class="row">
<div class="col-sm-4">
<label for="field_administrative_area_level_1">State</label>
<input id="field_administrative_area_level_1" type="text" />
</div>
<div class="col-sm-4">
<label for="field_postal_code">Zipcode</label>
<input id="field_postal_code" type="text" />
</div>
<div class="col-sm-4">
<label for="field_country">Country</label>
<input id="field_country" type="text" />
</div>
</div>
<div class="row">
<div class="col-sm-6">
<label for="field_latitude">Latitude</label>
<input id="field_latitude" type="text" />
</div>
<div class="col-sm-6">
<label for="field_longitude">Longitude</label>
<input id="field_longitude" type="text" />
</div>
<div class="col-sm-12">
<label for="field_formatted_address">Formatted Address</label>
<input type="text" id="field_formatted_address" />
</div>
</div>
</div>
Related
I have to create google maps direction service between 2 points / markers on map click event
I have prepared fiddle to illustrate how when you click on the map for a second time, a third marker is being printed on the map. Whatever I tried I could not succeed to remove the third marker.
The first marker has label A, second B, but the third is just being printed..
I will appreciate your time and help in solving this issue.
here is the fiddle
code snippet
var map;
function calculateAndDisplayRoute(directionsService, directionsRenderer) {
directionsService.route({
origin: {
query: document.getElementById('departure_address').value
},
destination: {
query: document.getElementById('arrival_address').value
},
travelMode: 'DRIVING'
},
function(response, status) {
if (status === 'OK') {
var point = response.routes[0].legs[0];
console.log(point);
directionsRenderer.setDirections(response);
} else {
alert('Directions request failed due to ' + status);
}
});
}
function initMap_mobile() {
var directionsService = new google.maps.DirectionsService();
var directionsRenderer = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('mobilemap'), {
mapTypeControl: false,
center: {
lat: 42.700000762939,
lng: 23.333299636841
},
zoom: 13
});
directionsRenderer.setMap(map);
var marker;
var infowindow;
google.maps.event.addListener(map, 'click', function(event) {
//alert(marker.length);
var dep_lat = $('#dep_lat').val();
var dep_lng = $('#dep_lng').val();
var arr_lat = $('#arr_lat').val();
var arr_lng = $('#arr_lng').val();
//alert(event.latLng.lat() +"-"+ event.latLng.lng());
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': new google.maps.LatLng(event.latLng.lat(), event.latLng.lng())
}, function(results, status) {
//alert(results[0].formatted_address); //Final address from lat and lng
//otherwise clicks twice
set_lat_long(event.latLng.lat(), event.latLng.lng(), results[0].formatted_address, directionsService, directionsRenderer);
//placeMarker(event.latLng, map, results[0].formatted_address)
//alert();
if (marker == null) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
//marker = placeMarker(event.latLng, map, results[0].formatted_address) ;
} else {
marker.setPosition(event.latLng);
//infowindow.open(map, marker);
}
});
});
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsRenderer);
};
document.getElementById('departure_address').addEventListener('change', onChangeHandler);
document.getElementById('arrival_address').addEventListener('change', onChangeHandler);
}
function set_lat_long(lat, lng, address, directionsService, directionsRenderer) {
var dep_lat = $('#dep_lat').val();
var dep_lng = $('#dep_lng').val();
var arr_lat = $('#arr_lat').val();
var arr_lng = $('#arr_lng').val();
if (isEmpty(dep_lat) || isEmpty(dep_lng)) {
//alert(dep_lat);
$('#dep_lat').val(lat);
$('#dep_lng').val(lng);
$('#departure_address').val(address);
$('#clear_dep').show();
} else {
//alert(dep_lat);
if (isEmpty(arr_lat) || isEmpty(arr_lng)) {
$('#arr_lat').val(lat);
$('#arr_lng').val(lng);
$('#arrival_address').val(address);
$('#clear_arr,.arrival_address').show();
}
}
if (!isEmpty($('#dep_lat').val()) && !isEmpty($('#dep_lng').val()) && !isEmpty($('#arr_lat').val()) && !isEmpty($('#arr_lng').val())) calculateAndDisplayRoute(directionsService, directionsRenderer);
}
function isEmpty(value) {
return (value == null || value.length === 0);
}
initMap_mobile();
#mobilemap {
height: 500px;
width: 100%;
border: solid 1px #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div class="cell-xs-12 mobw100 npr">
<div class="form-group text-right">
<label for="departure_address" class="form-label">From</label>
<input maxlength="100" id="departure_address" placeholder="From address" type="text" name="departure_address" class="controls form-control form-control-gray-base dybck" value="" style="background: rgb(255, 236, 236) none repeat scroll 0% 0%;" autocomplete="off">
<input type="hidden" name="dep_lat" id="dep_lat" value="">
<input type="hidden" name="dep_lng" id="dep_lng" value="">
</div>
</div>
<div class="cell-xs-12 offset-top-20 mobw100 npr he arrival_address">
<div class="form-group text-right">
<label for="arrival_address" class="form-label">To</label>
<input maxlength="100" id="arrival_address" placeholder="To address" type="text" name="arrival_address" class="controls form-control form-control-gray-base" value="" autocomplete="off">
<input type="hidden" name="arr_lat" id="arr_lat" value="">
<input type="hidden" name="arr_lng" id="arr_lng" value="">
</div>
</div>
<div id="mobilemap"></div>
To hide the "click" marker (leaving the ones the DirectionsRenderer displays):
move the marker to the global scope (where the map variable is):
var map;
var marker;
hide the marker in the DirectionsService callback function when the route is displayed:
function(response, status) {
if (status === 'OK') {
var point = response.routes[0].legs[0];
console.log(point);
directionsRenderer.setDirections(response);
if (marker && marker.setMap) // hide click marker when directions displayed
marker.setMap(null);
} else {
alert('Directions request failed due to ' + status);
}
}
proof of concept fiddle
var map;
var marker; // move marker definition into the global scope
function calculateAndDisplayRoute(directionsService, directionsRenderer) {
directionsService.route({
origin: {
query: document.getElementById('departure_address').value
},
destination: {
query: document.getElementById('arrival_address').value
},
travelMode: 'DRIVING'
},
function(response, status) {
if (status === 'OK') {
var point = response.routes[0].legs[0];
console.log(point);
directionsRenderer.setDirections(response);
if (marker && marker.setMap) // hide click marker when directions displayed
marker.setMap(null);
} else {
alert('Directions request failed due to ' + status);
}
});
}
function initMap_mobile() {
var directionsService = new google.maps.DirectionsService();
var directionsRenderer = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('mobilemap'), {
mapTypeControl: false,
center: {
lat: 42.700000762939,
lng: 23.333299636841
},
zoom: 13
});
directionsRenderer.setMap(map);
var infowindow;
google.maps.event.addListener(map, 'click', function(event) {
//alert(marker.length);
var dep_lat = $('#dep_lat').val();
var dep_lng = $('#dep_lng').val();
var arr_lat = $('#arr_lat').val();
var arr_lng = $('#arr_lng').val();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': new google.maps.LatLng(event.latLng.lat(), event.latLng.lng())
}, function(results, status) {
//otherwise clicks twice
set_lat_long(event.latLng.lat(), event.latLng.lng(), results[0].formatted_address, directionsService, directionsRenderer);
if (marker == null) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
} else {
marker.setPosition(event.latLng);
}
});
});
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsRenderer);
};
document.getElementById('departure_address').addEventListener('change', onChangeHandler);
document.getElementById('arrival_address').addEventListener('change', onChangeHandler);
}
function set_lat_long(lat, lng, address, directionsService, directionsRenderer) {
var dep_lat = $('#dep_lat').val();
var dep_lng = $('#dep_lng').val();
var arr_lat = $('#arr_lat').val();
var arr_lng = $('#arr_lng').val();
if (isEmpty(dep_lat) || isEmpty(dep_lng)) {
//alert(dep_lat);
$('#dep_lat').val(lat);
$('#dep_lng').val(lng);
$('#departure_address').val(address);
$('#clear_dep').show();
} else {
if (isEmpty(arr_lat) || isEmpty(arr_lng)) {
$('#arr_lat').val(lat);
$('#arr_lng').val(lng);
$('#arrival_address').val(address);
$('#clear_arr,.arrival_address').show();
}
}
if (!isEmpty($('#dep_lat').val()) && !isEmpty($('#dep_lng').val()) && !isEmpty($('#arr_lat').val()) && !isEmpty($('#arr_lng').val())) calculateAndDisplayRoute(directionsService, directionsRenderer);
}
function isEmpty(value) {
return (value == null || value.length === 0);
}
initMap_mobile();
#mobilemap {
height: 500px;
width: 100%;
border: solid 1px #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div class="cell-xs-12 mobw100 npr">
<div class="form-group text-right">
<label for="departure_address" class="form-label">From</label>
<input maxlength="100" id="departure_address" placeholder="From address" type="text" name="departure_address" class="controls form-control form-control-gray-base dybck" value="" style="background: rgb(255, 236, 236) none repeat scroll 0% 0%;" autocomplete="off">
<input type="hidden" name="dep_lat" id="dep_lat" value="">
<input type="hidden" name="dep_lng" id="dep_lng" value="">
</div>
</div>
<div class="cell-xs-12 offset-top-20 mobw100 npr he arrival_address">
<div class="form-group text-right">
<label for="arrival_address" class="form-label">To</label>
<input maxlength="100" id="arrival_address" placeholder="To address" type="text" name="arrival_address" class="controls form-control form-control-gray-base" value="" autocomplete="off">
<input type="hidden" name="arr_lat" id="arr_lat" value="">
<input type="hidden" name="arr_lng" id="arr_lng" value="">
</div>
</div>
<div id="mobilemap"></div>
I want to be able to show multiple markers when I insert something in to searchboxes on the website. Right now I have 3 input fields which I want to increase. This is what I currently have, I have tried storing multiple searchBox values in a var like so: var markers = searchBox.getPlaces(), searchBox.getPlaces1(), searchBox.getPlaces2()
How do I extend this code to additional input fields?
<input id="pac-input" class="controls" type="text" placeholder="Search Box" /><br />
<input id="pac-input1" class="controls" type="text" placeholder="Search Box" />
<input id="pac-input2" class="controls" type="text" placeholder="Search box" />
<div id="map"></div>
<script>
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 52.728616, lng: 6.4901 },
zoom: 13,
mapTypeId: 'roadmap'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var input1 = document.getElementById('pac-input1');
var input2 = document.getElementById('pac-input2');
var searchBox = new google.maps.places.SearchBox(input);
var searchBox1 = new google.maps.places.SearchBox(input1);
var searchBox2 = new google.maps.places.SearchBox(input2);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input1);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
searchBox1.setBounds(map.getBounds());
searchBox2.setBounds(map.getBounds());
});
var markers = [];
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function (marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
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)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=[APIKEY]&libraries=places&callback=initAutocomplete"
async defer></script>
related question (for autocomplete): Google Maps API autocomplete 2nd address fields on same page
Get the array of <input> elements you want to use for the SearchBox, use those to create the SearchBox objects, create a function that takes the unique identifier for the SearchBox and a reference to the SearchBox object. Use that function to process the events from each of the SearchBox objects.
var searchBoxes = document.getElementsByClassName('controls');
for (var i=0; i<searchBoxes.length;i++) {
var searchBox = new google.maps.places.SearchBox(searchBoxes[i]);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(searchBoxes[i]);
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
markers.push([]);
searchBox.addListener('places_changed', (function(i) {
return function() {
processSearch(i, this)
}
}(i)));
}
processSearch function:
function processSearch(uniqueId, searchBox) {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers[uniqueId].forEach(function(marker) {
marker.setMap(null);
});
markers[uniqueId] = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
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)
};
// Create a marker for each place.
if (!markers[uniqueId]) markers.push([]);
markers[uniqueId].push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
}
proof of concept fiddle
code snippet:
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
.controls {
width: 100px;
}
<input id="pac-input" class="controls" type="text" placeholder="Search Box" />
<input id="pac-input1" class="controls" type="text" placeholder="Search Box" />
<input id="pac-input2" class="controls" type="text" placeholder="Search box" />
<input id="pac-input3" class="controls" type="text" placeholder="Search box" />
<input id="pac-input4" class="controls" type="text" placeholder="Search box" />
<input id="pac-input5" class="controls" type="text" placeholder="Search box" />
<div id="map"></div>
<script>
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 52.728616,
lng: 6.4901
},
zoom: 13,
mapTypeId: 'roadmap'
});
var markers = [];
// Create the search boxs and link them to the UI elements.
var searchBoxes = document.getElementsByClassName('controls');
for (var i = 0; i < searchBoxes.length; i++) {
var searchBox = new google.maps.places.SearchBox(searchBoxes[i]);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(searchBoxes[i]);
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
markers.push([]);
searchBox.addListener('places_changed', (function(i) {
return function() {
processSearch(i, this)
}
}(i)));
}
function processSearch(uniqueId, searchBox) {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers[uniqueId].forEach(function(marker) {
marker.setMap(null);
});
markers[uniqueId] = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
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)
};
// Create a marker for each place.
if (!markers[uniqueId]) markers.push([]);
markers[uniqueId].push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initAutocomplete" async defer></script>
I know many thread discuss this but my code still doesn't work.
I'm using google places searchBox API.
My code:
function initMap(){
var map = new google.maps.Map(document.getElementById('peta'), {
center: {lat: -34.397, lng: 150.644},
zoom: 16
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Your Location.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
var input = document.getElementById('alamat');
var searchBox = new google.maps.places.SearchBox(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
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)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
document.getElementById('x').innerHTML(places.geometry.location.lat());
});
}
link script:
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&libraries=places"></script>
html:
<div id="peta" style="width:500px;height:380px;"></div>
<input type="text" id="x" readonly="readonly" name="x">
i put document.getElementById on my textbox but it still doesn't show the latitude. Where i should put this code?
in other thread:
var location= places.geometry.location;
var lat = location.lat();
but it's not working. How do I solve the problem?
Is your element #x an input text box?
If so try:
document.getElementById('x').value = places.geometry.location.lat();
That will add the latitude to the value of the input text box.
Is this what you are trying to achieve?
I've solve the problem.
as #Dammeul said, i place the
document.getElementById('x').value = place.geometry.location.lat();
inside of places.forEach(function (place))
Hope this helpful.
It will convert the address into latitude and longitude and also show the address in the map with the marker..You have just add your map API key
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
function initMap() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(23.684994, 90.35633099999995);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == '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);
}
});
}
function showResult(result) {
document.getElementById('latitude').value = result.geometry.location.lat();
document.getElementById('longitude').value = result.geometry.location.lng();
}
function getLatitudeLongitude(callback, address) {
address = address || 'Dhaka,Bangladesh';
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback(results[0]);
}
});
}
}
var button = document.getElementById('show');
button.addEventListener("click", function () {
var address = document.getElementById('address').value;
getLatitudeLongitude(showResult, address)
});
</script>
<!doctype html>
<html>
<head>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 400px;
width: 800px;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body onload="initMap()">
<div>
<div id="map" style="width: 320px; height: 480px;"></div>
<div>
<input id="address" type="textbox" value="">
<input type="button" id="show" value="Show" onclick="codeAddress()">
</div>
<div>
<p>Latitude:
<input type="text" id="latitude" readonly />
</p>
<p>Longitude:
<input type="text" id="longitude" readonly />
</p>
</div>
</body>
</html>
const { GoogleMap, LoadScript } = require("../../");
const ScriptLoaded = require("../../docs/ScriptLoaded").default;
const mapContainerStyle = {
height: "400px",
width: "800px"
};
const center = {
lat: 38.685,
lng: -115.234
};
const onLoad = ref => this.searchBox = ref;
const onPlacesChanged = () => {
x = this.searchBox.getPlaces()
console.log(x[0]["geometry"]["location"].lat())
}
<ScriptLoaded>
<GoogleMap
id="searchbox-example"
mapContainerStyle={mapContainerStyle}
zoom={2.5}
center={center}
>
<StandaloneSearchBox
onLoad={onLoad}
onPlacesChanged={
onPlacesChanged
}
>
<input
type="text"
placeholder="Customized your placeholder"
style={{
boxSizing: `border-box`,
border: `1px solid transparent`,
width: `240px`,
height: `32px`,
padding: `0 12px`,
borderRadius: `3px`,
boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
fontSize: `14px`,
outline: `none`,
textOverflow: `ellipses`,
position: "absolute",
left: "50%",
marginLeft: "-120px"
}}
/>
</StandaloneSearchBox>
</GoogleMap>
</ScriptLoaded>
Hi, i tried this, and it works, i get the lat and long, I am using react+searchboxAPI please feel free to follow up, here is the documentation, I realised that you cant do x["geometry"]["location"].lat(), instead you'll need to iterate through each of the places that have been returned, to test it, I did
console.log( x[0]["geometry"]["location"].lat() ) just to get the first result.You can use the js map function or iterate through the array of 20 by using a for loop.. cheers
https://react-google-maps-api-docs.netlify.app/#!/StandaloneSearchBox/1
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>
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">