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>
Related
I am working on core PHP, i wants to fecth location based record.
i want exact search for google map,like if i search (implemented autocomplete search) for (BTM layout) means BTM layout google map should come how will do this please help any one.
Here is my HTML form:
<form action="pglist.php" id="location_search" class="form-inline" method="POST" >
<div class="form-group keyword">
<input id="locationTextField" name= "list" type="text" size="50">
<button type="submit" name="filter"><img src="assets/images/search.png" alt="Rentozy" /></button>
</div>
</form>
Here is my database query:
$locations=array();
$query = $conn->query('SELECT `pg_address` FROM `tbl_master_property`');
while ($row = $query->fetch_assoc()) {
$locations[] = $row['pg_address'];
}
$locations = json_encode($locations);
Here my google map script code:
<div class="map">
<div id="map"></div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyBAM5Cs2VsrOBs8Idqy0t0o6vw4hEU0Lys">
</script>
<script type="text/javascript">
var delay = 100;
var infowindow = new google.maps.InfoWindow();
var latlng = new google.maps.LatLng(12.9716, 77.5946);
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var bounds = new google.maps.LatLngBounds();
function geocodeAddress(address, next) {
geocoder.geocode({address:address}, function (results,status)
{
if (status == google.maps.GeocoderStatus.OK) {
var p = results[0].geometry.location;
var lat=p.lat();
var lng=p.lng();
createMarker(address,lat,lng);
}
else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
nextAddress--;
delay++;
} else {
}
}
next();
}
);
}
function createMarker(add,lat,lng) {
var contentString = add;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
animation: google.maps.Animation.DROP,
draggable: true,
map: map,
});
marker.addListener('click', toggleBounce);
function toggleBounce() {
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
bounds.extend(marker.position);
}
var locations = <?= $locations ?>;
console.log(locations);
var nextAddress = 0;
function theNext() {
if (nextAddress < locations.length) {
setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
nextAddress++;
} else {
map.fitBounds(bounds);
}
}
theNext();
</script>
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': 'BTM layout'}, function(results, status) {
if (status === 'OK') {
Map.setCenter(results[0].geometry.location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
You could request the location using geocoder and handle exceptions.
I am having google map with 20 markers popup window is there.
Now, I want to capture details of all the markers show up as list(one by one). How can I do this below?
I have pasted my whole code HTML+Javascript
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Search Near by location</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<style type="text/css">
#map {
height: 400px;
width: 600px;
border: 1px solid #333;
margin-top: 0.6em;
}
</style>
<script type="text/javascript">
$(function(){
//get the checked nearby place
$('.case').click(function(){
$(':checkbox').attr('checked',false);
$('#'+$(this).attr('id')).attr('checked',true);
search_types(map.getCenter());
});
});
var map;
var infowindow;
var markersArray = [];
var pyrmont = new google.maps.LatLng(20.268455824834792, 85.84099235520011);
var marker;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
// var waypoints = [];
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 14
});
infowindow = new google.maps.InfoWindow();
//document.getElementById('directionsPanel').innerHTML='';
search_types();
}
function createMarker(place,icon) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon,
visible:true
});
markersArray.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent("<b>Name:</b>"+place.name+"<br><b>Address:</b>"+place.vicinity+"<br><b>Reference:</b>"+place.reference+"<br><b>Rating:</b>"+place.rating+"<br><b>Id:</b>"+place.id);
infowindow.open(map, this);
//get the clicked ATM name
document.getElementById("demo").innerHTML=place.name;
// get the ATM address
document.getElementById("demo1").innerHTML=place.vicinity;
});
}
var source="";
var dest='';
function search_types(latLng){
clearOverlays();
if(!latLng){
var latLng = pyrmont;
}
var type = $('.case:checked').val();
var icon = "https://cdn2.iconfinder.com/data/icons/banking-7/24/banking-atm-1-48.png";
var request = {
location: latLng,
radius: 2500,
types: [type] //e.g. school, restaurant,bank,bar,city_hall,gym,night_club,park,zoo
};
var service = new google.maps.places.PlacesService(map);
service.search(request, function(results, status) {
map.setZoom(14);
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
results[i].html_attributions='';
createMarker(results[i],icon);
}
}
});
}
// Deletes all markers in the array by removing references to them
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setVisible(false)
}
//markersArray.length = 0;
//document.getElementById("demo3").innerHTML = markersArray.length;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
function clearMarkers(){
$('#show_btn').show();
$('#hide_btn').hide();
clearOverlays()
}
function showMarkers(){
$('#show_btn').hide();
$('#hide_btn').show();
if (markersArray) {
for (i in markersArray) {
markersArray[i].setVisible(true)
}
}
}
function showMap(){
var imageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=FFFFFF,008CFF,000000&ext=.png';
var markerImage = new google.maps.MarkerImage(imageUrl,new google.maps.Size(24, 32));
var input_addr=$('#address').val();
geocoder.geocode({address: input_addr}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng(latitude, longitude);
if (results[0]) {
map.setZoom(14);
map.setCenter(latlng);
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: markerImage,
draggable: true
});
$('#btn').hide();
$('#latitude,#longitude').show();
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
search_types(marker.getPosition());
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#btn').hide();
$('#latitude,#longitude').show();
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
}
infowindow.setContent(results[0].formatted_address);
var centralLatLng = marker.getPosition();
search_types(centralLatLng);
infowindow.open(map, marker);
}
});
});
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
</SCRIPT>
</head>
<body>
<label>Address: </label><input id="address" type="text" style="width:400px;" value=""/>
<label class="btn btn-primary">
<input type="checkbox" name="mytype" class="case btn btn-primary" id="btn" value="atm" onClick="showMap();">ATM
</label>
<br/>
<div id="map"></div>
<input type="text" id="latitude" style="display:none;" placeholder="Latitude"/>
<input type="text" id="longitude" style="display:none;" placeholder="Longitude"/>
<!-- <input type="button" id="hide_btn" value="hide markers" onClick="clearMarkers();" />-->
<input type="button" id="show_btn" value="atm" onClick="showMarkers();" style="display:none;" />
<div id="test"></div>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo3"></p>
</body>
</html>
One option would be to capture the data you want to display under the map in a appropriately scoped variable as you create the markers (in the createMarker function):
htmlStr += "<tr><td><b>Name:</b>" + place.name + "<br><b>Address:</b>" + place.vicinity + "<br><b>Reference:</b>" + place.reference + "<br><b>Rating:</b>" + place.rating + "<br><b>Id:</b>" + place.id + "</td></tr>";
Initialize the variable before the loop that creates the markers, finish it and put it in the div you want to display it at the end of the loop:
if (status == google.maps.places.PlacesServiceStatus.OK) {
htmlStr = "<table border='1'><tbody>";
for (var i = 0; i < results.length; i++) {
results[i].html_attributions = '';
createMarker(results[i], icon);
}
document.getElementById("demo").innerHTML = htmlStr + "</tbody></table>";
}
code snippet:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Search Near by location</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<style type="text/css">
#map {
height: 400px;
width: 600px;
border: 1px solid #333;
margin-top: 0.6em;
}
</style>
<script type="text/javascript">
$(function() {
//get the checked nearby place
$('.case').click(function() {
$(':checkbox').attr('checked', false);
$('#' + $(this).attr('id')).attr('checked', true);
search_types(map.getCenter());
});
});
var map;
var htmlStr = '';
var infowindow;
var markersArray = [];
var pyrmont = new google.maps.LatLng(20.268455824834792, 85.84099235520011);
var marker;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 14
});
infowindow = new google.maps.InfoWindow();
search_types();
}
function createMarker(place, icon) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon,
visible: true
});
markersArray.push(marker);
htmlStr += "<tr><td><b>Name:</b>" + place.name + "<br><b>Address:</b>" + place.vicinity + "<br><b>Reference:</b>" + place.reference + "<br><b>Rating:</b>" + place.rating + "<br><b>Id:</b>" + place.id + "</td></tr>";
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent("<b>Name:</b>" + place.name + "<br><b>Address:</b>" + place.vicinity + "<br><b>Reference:</b>" + place.reference + "<br><b>Rating:</b>" + place.rating + "<br><b>Id:</b>" + place.id);
infowindow.open(map, this);
});
}
var source = "";
var dest = '';
function search_types(latLng) {
clearOverlays();
if (!latLng) {
var latLng = pyrmont;
}
var type = $('.case:checked').val();
var icon = "https://cdn2.iconfinder.com/data/icons/banking-7/24/banking-atm-1-48.png";
var request = {
location: latLng,
radius: 2500,
types: [type] //e.g. school, restaurant,bank,bar,city_hall,gym,night_club,park,zoo
};
var service = new google.maps.places.PlacesService(map);
service.search(request, function(results, status) {
map.setZoom(14);
if (status == google.maps.places.PlacesServiceStatus.OK) {
htmlStr = "<table border='1'><tbody>";
for (var i = 0; i < results.length; i++) {
results[i].html_attributions = '';
createMarker(results[i], icon);
}
document.getElementById("demo").innerHTML = htmlStr + "</tbody></table>";
}
});
}
// Deletes all markers in the array by removing references to them
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setVisible(false)
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
function clearMarkers() {
$('#show_btn').show();
$('#hide_btn').hide();
clearOverlays()
}
function showMarkers() {
$('#show_btn').hide();
$('#hide_btn').show();
if (markersArray) {
for (i in markersArray) {
markersArray[i].setVisible(true)
}
}
}
function showMap() {
var imageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=FFFFFF,008CFF,000000&ext=.png';
var markerImage = new google.maps.MarkerImage(imageUrl, new google.maps.Size(24, 32));
var input_addr = $('#address').val();
geocoder.geocode({
address: input_addr
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng(latitude, longitude);
if (results[0]) {
map.setZoom(14);
map.setCenter(latlng);
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: markerImage,
draggable: true
});
$('#btn').hide();
$('#latitude,#longitude').show();
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
search_types(marker.getPosition());
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({
'latLng': marker.getPosition()
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#btn').hide();
$('#latitude,#longitude').show();
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
}
infowindow.setContent(results[0].formatted_address);
var centralLatLng = marker.getPosition();
search_types(centralLatLng);
infowindow.open(map, marker);
}
});
});
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
$(function() {
// add multiple select / deselect functionality
$("#selectall").click(function() {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function() {
if ($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
</SCRIPT>
</head>
<body>
<label>Address:</label>
<input id="address" type="text" style="width:400px;" value="" />
<label class="btn btn-primary">
<input type="checkbox" name="mytype" class="case btn btn-primary" id="btn" value="atm" onClick="showMap();">ATM
</label>
<br/>
<div id="map"></div>
<input type="text" id="latitude" style="display:none;" placeholder="Latitude" />
<input type="text" id="longitude" style="display:none;" placeholder="Longitude" />
<!-- <input type="button" id="hide_btn" value="hide markers" onClick="clearMarkers();" />-->
<input type="button" id="show_btn" value="atm" onClick="showMarkers();" style="display:none;" />
<div id="test"></div>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo3"></p>
</body>
</html>
I think, MarkersArray contains everything you need. Lets loop trough it.
for(i=0;i<MarkersArray;i++){
marker=MarkersArray[i];
container=document.body;//change to your element
//create a new paragraph, and add it to the marker (if you need to change it later)
marker.html=document.createElement("p");
//add the name and vicinity to the paragraph
marker.html.innerHTML=marker.name+":"+marker.vicinity;
//put it on the site (into the container)
container.appendChild(marker.html);
}
I am doing programming in codeigniter + ajax + javascript and I have to fetch the longitude and latitude based on the user's entry in textbox.
I am already get the right response from the controller but view is not able to convert those longitude and latitude into maps even maps are not load on the page.
Here you can see my code:
$(document).ready(function() {
function submitMe(selector)
{
//alert(selector);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/locationcontroller/getLocation",
data: {location:selector },
success:function(longitude){
// alert(selector);
locate=longitude.split(" ");
latlong(locate[0],locate[1],selector);
}
});
}
$('#address').blur(function(){
var add=$('#address').val();
// alert(add);
submitMe(add);
});
});
function latlong(lat,long,selector)
{
alert(lat);
alert(long);
var selector=selector;
var myLatlng = new google.maps.LatLng(lat,long);
var map;
var marker;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function initialize(){
var mapOptions = {
zoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("myMap"), mapOptions);
marker = new google.maps.Marker({
map: map,
position: myLatlng,
draggable: true
});
geocoder.geocode({'latLng': myLatlng }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#latitude,#longitude').show();
selector=results[0].formatted_address;
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
selector=results[0].formatted_address;
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
}
#myMap {
height: 350px;
width: 680px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<form method="POST">
<div id="myMap"></div>
<!--<input id="" type="text" style="width:600px;"/><br/>-->
<input type="text" id="address" name="address" />
<input type="text" id="latitude" placeholder="Latitude"/>
<input type="text" id="longitude" placeholder="Longitude"/>
<input type="submit" name="submit">
</form>
code of view
code of the controller
Change your javascript to
$(document).ready(function () {
function submitMe(selector) {
//alert(selector);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/locationcontroller/getLocation",
data: { location: selector },
//success: function (longitude) {
error: function (longitude) { // error because jsfiddle doesn't support ajax
//alert(selector);
longitude = "1.0001203013 12.0000001";
locate = longitude.split(" ");
latlong(locate[0], locate[1]);
}
});
}
$('#address').blur(function () {
var add = $('#address').val();
// alert(add);
submitMe(add);
});
});
function latlong(lat, long) {
alert(lat);
alert(long);
var myLatlng = new google.maps.LatLng(lat, long);
initialize(myLatlng);
}
// RELEVANT CHANGE: move initialize function outside of latlng, and receives the coordinates as parameter.
function initialize(myLatlng) {
var map;
var marker;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var mapOptions = {
zoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("myMap"), mapOptions);
marker = new google.maps.Marker({
map: map,
position: myLatlng,
draggable: true
});
geocoder.geocode({ 'latLng': myLatlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#latitude,#longitude').show();
selector = results[0].formatted_address;
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
google.maps.event.addListener(marker, 'dragend', function () {
geocoder.geocode({ 'latLng': marker.getPosition() }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
selector = results[0].formatted_address;
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', function () {
// RELEVANT CHANGE: initialize function receives an initial value.
var initialLatlng = new google.maps.LatLng(1.55555, 10.55555);
initialize(initialLatlng);
});
#myMap {
height: 350px;
width: 680px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<form method="POST">
<div id="myMap"></div>
<!--<input id="" type="text" style="width:600px;"/><br/>-->
<input type="text" id="address" name="address" />
<input type="text" id="latitude" placeholder="Latitude"/>
<input type="text" id="longitude" placeholder="Longitude"/>
<input type="submit" name="submit" />
</form>
Relevant changes
move initialize function outside of latlng, and now receives the
coordinates as parameter.
initialize function receives an initial value
JSFiddle demo
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">
Do you have any idea why my directions service of Google Maps API doesn't work? It seems that method directionsService.route() isn't executed (cause alert with status is not displayed), but I don't know why. I'm newbie in Google Maps API and JS, so try to be forgiving, if it's something simple. :)
var map = null;
var pos = null;
const STORED_LOC = new google.maps.LatLng(50.405196, 11.894855);
var currentLat = document.getElementById("latLabel");
var currentLng = document.getElementById("lngLabel");
var additionalInfo = document.getElementById("additionalInfo");
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize()
{
pos = STORED_LOC;
currentLat.innerHTML = pos.lat();
currentLng.innerHTML = pos.lng();
options =
{
center: pos,
zoom: 15
}
marker = new google.maps.Marker(
{
position: pos,
map: map,
title: "Chosen localization"
}
);
map = new google.maps.Map(document.getElementById("mapContainer"), options);
marker.setMap(map);
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
}
$("#yes").click(function () {
getPosition();
hideUserConsentSection();
});
$("#no").click(function () {
hideUserConsentSection();
showSetCustomLocationSection();
});
function showSetCustomLocationSection() {
$("#setCustomLocationSection").show();
}
function hideUserConsentSection() {
$("#userConsentSection").hide();
}
function getPosition() {
if (navigator.geolocation) {
var options = {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 2000
}
navigator.geolocation.getCurrentPosition(showPosition, errorPosition, options);
}
else
{
additionalInfo.innerHTML += "Your browser doesn't support geolocation";
}
}
function showPosition(position) {
pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
currentLat.innerHTML = pos.lat();
currentLng.innerHTML = pos.lng();
var request =
{
origin: STORED_LOC,
destination: pos,
travelmode: google.maps.TravelMode.DRIVING
}
directionsService.route(request, function(result, status)
{
alert(status);
if (status == google.maps.DirectionsStatus.OK)
{
alert("OKAY");
directionsDisplay.setDirections(result);
}
});
//map = new google.maps.Map(document.getElementById("mapContainer"), options);
//marker.setMap(map);
}
function errorPosition(position) {
switch (position.code) {
case 1:
showSetCustomLocationSection();
break;
case 2:
showSetCustomLocationSection();
break;
case 3:
showSetCustomLocationSection();
break;
default:
break;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
My HTML looks like that:
<h3>How to reach us?</h3>
<div id="userConsentSection">Can we use your geolocation?<br />
<input type="button" id="yes" value="Yes" />
<input type="button" id="no" value="No" /><br /><br />
</div>
<div id="setCustomLocationSection" style="display:none">
Enter your geolocation. <br /><br />
<input type="text" id="customLocation" />
<input type="button" id="setCustomLocationButton" value="Show" /><br /><br />
</div>
<span>Latitude: </span>
<div id="latLabel">
</div>
<span>Longitude: </span>
<div id="lngLabel">
</div>
<div id="additionalInfo">
</div>
<div id="mapContainer" style="height: 400px; width: 100%">
</div>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=XXXX&sensor=true">
</script>
The answer is typo in request object - travelmode instead travelMode. This parameter is required and as the result - route method doesn't execute. Be careful with that name!