I am trying to make a call to google maps api to display driving directions based on 2 inputted locations. My skill level is newb.
I am using a notepad to render my html (by pressing ctrl+shift+alt+R), I also tried using xampp to host a local server and then open my html on local (by placing it into htdocs file). While using both of those methods of rendering, each time I input my addresses, the map just blinks and no results are displayed. Is the issue my code or the way I am rendering it? If its the way I am rendering it, could someone please suggest another way I could see/render my html? Thank you very much. Martin
Code:
<!DOCTYPE html>
<html>
<head profile="http://gmpg.org/xfn/11"><style type="text/css">.gm-style .gm-style-mtc
label,.gm-style .gm-style-mtc div{font-weight:400}</style>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% ;position:relative;z-index:1}
#panel {
position: fixed;
bottom: 35px;
background: rgba(99,99,99,0.7);
width: 97.75%;
border:3px solid; #FF3D03
border-radius:3px;
z-index: 15;
font-weight: bold;
font-family: arial;
font-style: normal;
padding: 2px 0px 2px 24px;
}
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?
key=AIzaSyAzbS2nerrvbdvNlsyQO9cDWFNthdoswRU&sensor=false">
</script>
<div id="map_canvas">
<script type="text/javascript">
var address = new google.maps.LatLng(31.208647, 7.861769);
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
<!------------------------------------------------------->
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
center: address,
zoom: 16,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
directionsDisplay.setMap(map);
}
<!------------------------------------------------------->
function calcRoute() {
var start = document.forms["frame1"]["address0"].value;
var end = document.forms["frame1"]["address1"].value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
<!------------------------------------------------------->
// var myTitle = document.createElement('h1');
// myTitle.style.color = 'red';
// myTitle.innerHTML = 'menu would go here';
// var myTextDiv = document.createElement('div');
// myTextDiv.appendChild(myTitle);
// map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(myTextDiv);
// var marker = new google.maps.Marker({
// position: new google.maps.LatLng(33.6803003, -116.173894),
// title: "Festival" });
// marker.setMap(map);}
<!------------------------------------------------------->
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</div>
</head>
<!-------------------------------------------------------------------------------->
<body>
<!------------------------------------------------------->
<!-------------------------------------------------------->
<div id="panel" style="color:#ffffff; font-size:18px;" >
<form name="frame1" onsubmit="calcRoute();">
<b>Start: </b>
<input type="text" name="address0">
<b>First Address: </b>
<input type="text" name="address1">
<input type="submit" style="visibility: hidden;">
</form>
</div>
<div id="map-canvas"/>
<!------------------------------------------------------->
<!------------------------------------------------------->
</body>
</html>
Your form submission is reloading the page, destroying the directions response. Change:
<form name="frame1" onsubmit="calcRoute();">
To:
<form name="frame1" onsubmit="calcRoute();return false;">
Related
I'm trying to build a small project where we get specific nearby places (schools, hospitals, cafes etc) around 5kms radius on clicking a radio button.Here I'm trying to use the geolocation to get the dynamic location(latitude and longitude) so that I can get user current location where ever this app is used.What happening is, the map is not loading on page load while the first radio button is already checked but it is working fine when I switch to other radio buttons.
I'm not an expert in JavaScript.
Below is my HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Google Maps</title>
<style>
#map {
height: 100%;
width: 100%;
}
#box{
height:500px;
width:80%;
margin-left:10%;
margin-right:10%;
border:2px solid black;
}
h1{
text-align:center;
font-family:sans-serif;
}
form {
text-align: center;
}
</style>
</head>
<body>
<h1>Google Maps</h1>
<form>
<input type="radio" id="school" name="places" value="School" checked onClick="load();">Schools
<input type="radio" id="hospital" name="places" value="Hospital" onClick="load();">Hospitals
<input type="radio" id="cafe" name="places" value="Hotel" onClick="load();">Cafes
<input type="radio" id="atm" name="places" value="atm" onClick="load();">ATM's
</form>
<br>
<div id="box">
<div id="map"></div>
</div>
<script type = "text/javascript" src="maps.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBVOCb1nOuIrbnvnTYIYTKMqs2y5ecuMi8&signed_in=true&libraries=places&callback=load" async defer></script>
</body>
</html>
Here's my JavaScript code
var map;
var infowindow;
var myLat;
var myLong;
x = navigator.geolocation;
x. getCurrentPosition(success);
function success(position){
myLat = position.coords.latitude;
myLong = position.coords.longitude;
}
function load() {
//var hyderabad = {lat: 17.46724, lng: 78.53591};
var hyderabad = new google.maps.LatLng(myLat , myLong);
map = new google.maps.Map(document.getElementById('map'), {
center: hyderabad,
zoom: 12
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
var place;
if (document.getElementById('school').checked) {
place = "school"
}
else if (document.getElementById('hospital').checked) {
place = "hospital"
}
else if (document.getElementById('cafe').checked) {
place = "cafe"
}
else if (document.getElementById('atm').checked) {
place = "atm"
}
service.nearbySearch({
location: hyderabad,
radius: 5000,
type: [place]
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
Messing around with the Google Maps API in a browser, however I'm having a bit of trouble putting in a user input for the variables. Essentially, I want to be able to put in a new lat/long from pressing a button on the page and have the map move onto that.
It doesn't work for the actual input variables, but when I use the commented out section it works perfectly fine.
<body>
<form id = "input" method = "get">
<input type = "text" placeholder = "Latitude" name = "user_lat">
<input type = "text" placeholder = "Longitude" name = "user_lng"><br>
<button type = "submit">Mark on Map</button>
</form>
<div id = "map"></div>
<script>
var lat_in = parseFloat($('#user_lat').val());
var lng_in = parseFloat($('#user_lng').val());
/*var lat_in = 37.697948;
var lng_in = -97.314835;*/
function initMap() {
var location = {lat: lat_in, lng: lng_in};
/*var location = {lat: 37.697948, lng: -97.314835};*/
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: location
});
var marker = new google.maps.Marker({
position: location,
map: map
});
}
</script>
<script async defer
src="link with the API key here">
</script>
I suspect it might have something to do how I actual use the submit button and the way I interact with it, but I'm not 100% sure. I've looked up different things, but I'm still a bit new at this. I just started to dabble in javascript, so I'm sure there are better methods to do this, but I just want to get this working to get an understanding of it.
You can do it like this, Add change listener and on change pan to that location by clicking enter
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Directions service</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
</style>
</head>
<body>
<div id="floating-panel">
<b>Start: </b>
<input id="start" type="text"
placeholder="Enter lat">
<b>End: </b>
<input id="end" type="text"
placeholder="Enter lng">
</div>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 0, lng: 0}
});
marker = new google.maps.Marker({
map:map,
draggable:true,
animation: google.maps.Animation.DROP,
position: {lat: 0, lng: 0}
});
var onChangeHandler = function() {
DisplayPoint(map);
};
//document.getElementById('start').addEventListener('change', onChangeHandler);
document.getElementById('end').addEventListener('change', onChangeHandler);
function DisplayPoint(map) {
var lat = document.getElementById('start').value;
var lng = document.getElementById('end').value;
var latLng = new google.maps.LatLng(lat, lng);
marker.setPosition(latLng);
map.panTo(latLng);
}
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=API_KEY_HERE&callback=initMap">
</script>
I want the map to update to the new Address given by the user when enter new Address in the search box. this is what I tried but is not working
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Street View service</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var lag =151.1956316;
var lat = -33.8665433;
function initialize() {
var fenway = new google.maps.LatLng( lat, lag);
var mapOptions = {
center: fenway,
zoom: 14
};
var map = new google.maps.Map(
document.getElementById('map-canvas'), mapOptions);
var panoramaOptions = {
position: fenway,
pov: {
heading: 34,
pitch: 10
}
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'),panoramaOptions);
map.setStreetView(panorama);
}
// search for new Addreess
var addressField = document.getElementById('search_address');
var geocoder = new google.maps.Geocoder();
function search() {
geocoder.geocode(
{'address': addressField.value},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var loc = results[0].geometry.location;
// use loc.lat(), loc.lng()
lat = loc.lat();
lag = loc.lng();
google.maps.event.addDomListener(window, 'load', initialize);
}
else {
alert("Not found: " + status);
}
}
);
};
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="width: 400px; height: 300px"></div>
<div id="pano" style="position:absolute; left:410px; top: 8px; width: 400px; height: 300px;"></div>
<div id="panel">
<input type="text" id="search_address" value=""/>
<button onclick="search();">Search</button>
</div>
</body>
</html>
it tried many option but still not working
There are 2 issues:
the addressField -variable has been defined too early(the input is unknown at this time)
modifying the lag/lat -variables will not have an effect to the map/panorama
(you must assign a LatLng to the center of the map/position of the panorama)
I have the following script which will load directions to Las Vegas from the browser location:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API v3 Directions Example</title>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body style="font-family: Arial; font-size: 12px;">
<div style="width: 600px;">
<div id="map" style="width: 280px; height: 400px; float: left;"></div>
<div id="panel" style="width: 300px; float: right;"></div>
</div>
<script type="text/javascript">
var mylat,mylong,request;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('map'), {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
navigator.geolocation.getCurrentPosition(GetLocation);
function GetLocation(location) {
mylat= location.coords.latitude;
mylong = location.coords.longitude;
request = {
origin: mylat+','+mylong,
destination: '35.580789,-105.210571',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
</script>
</body>
</html>
This works great for what I need, but as you can see this leaves some down time while the page loads. I would like to add a message that tells the user to hold while the directions are loading. From what I can tell I just need to add an event listener while loading. Here is the sample I am trying to use:
google.maps.event.addListenerOnce(map, 'idle', function(){
document.write("<p>please hold while loading</p>");
});
I have tried to add this to a few locations in the script, but it is not loading during the downtime, but rather after the page loads. Any suggestions on how I can adjust this listener in the code for display only during downtime?
Not sure but still try
<script type="text/javascript">
document.write("<p id='loader'>please hold while loading</p>");
.....
......
function GetLocation(location) {
............................
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
document.getElementById('loader').innerHTML = "Map loaded";
}
}
</script>
I'm dabbling a bit with google maps and data presentation and was wondering if it is possible to create a button on the map page to drop the markers.
I have no programming experience (I deal with SQL mainly) so any help appreciated - I have the following code taken from varying webistes:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
// Standard google maps function
function initialize() {
var myLatlng = new google.maps.LatLng(52.469397,-3.208008);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
TestMarker();
}
// Function for adding a marker to the page.
function addMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map,
animation: google.maps.Animation.DROP
});
}
// Testing the addMarker function
function TestMarker() {
Marker1=new google.maps.LatLng(52.268000,-3.043000); addMarker(Marker1);
Marker23=new google.maps.LatLng(51.524243,-3.193911); addMarker(Marker23);
Marker24=new google.maps.LatLng(51.524243,-3.193911); addMarker(Marker24);
Marker25=new google.maps.LatLng(51.524243,-3.193911); addMarker(Marker25);
Marker26=new google.maps.LatLng(51.524243,-3.193911); addMarker(Marker26);
Marker584=new google.maps.LatLng(51.747777,-3.500599); addMarker(Marker584);
Marker585=new google.maps.LatLng(51.608871,-3.647570); addMarker(Marker585);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="border: 1px solid black; width: 500px; height: 400px;">map div</div>
<p style="margin-top: 5px">
<button id="drop">Drop</button>
</p>
</body>
</html>
Now this creates a button, but I can't for the life of me work out how to link this back to my markers. I have found something here that I should be able to adapt but I just don't have the knowhow.
My markers are defined by a sql query, but for now I would like to be able to simply feed in a list and get a drop button to drop them when I click on it.
Any help massively appreciated :)
Remove the call to TestMarker from your initialize function. Then just add an onclick attribute to your button:
<button id="drop" onclick="TestMarker()">Drop</button>