Reputation: 7059
This is the code I'm using right now to call Google Maps API:
function initialize() {
var myLatlng = new google.maps.LatLng(41.88994,12.51383);
var mapOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Studio medico'
});
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?sensor=false&' + 'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
You can see this live here. If you try to click on "(calcola percorso)", near "Mezzi pubblici" an input box appears. That's the starting address (saddress) parameter because the "Go" button will take you to Google Maps website and Transit service (and bring you through Transit to an "hardcoded" destination address starting from the address you typed).
Now, is it possible to start Transit directly in the map called with the script above (without going to Google Maps website)? It would be awesome to have the users typing their address in the input form, clicking "Go" and then have the map above to be "turned" in Transit mode with a destination address I specify but the starting address selected by the users (from input form).
Upvotes: 1
Views: 291
Reputation: 28850
Yes, you can do this. You'll need to use the Directions
service in the Maps API. Here's an example page.
OK, so far so good! I took a look at your latest code, and you're definitely on the right track (pun intended). As I mentioned in the comment, the problem is that you're calling the same calcRoute()
function for both the select/option case and the text input form.
You could either break this into separate functions for each case, or perhaps use the same function but just pass in the element ID for each one. To do that, I'd give your text input field an ID:
<input type="text" id="startText" name="start" placeholder="Start address">
and then change your select element to pass its id:
<select id="start" onchange="calcRoute('start');">
and change the text input form too:
<form method="get" id="start" onsubmit="calcRoute('startText');" action="#" style="display:inline">
Now simply change the beginning of calcRoute()
:
function calcRoute( input ) {
var start = document.getElementById(input).value;
... remainder of existing code here ...
}
Or, as I mentioned in the comment, you could break these out into separate functions, perhaps calcRouteFromSelect()
and calcRouteFromText()
, and call each function from the respective form. These would each set up the input address as appropriate, and then call a common function to do the rest of the work. Either way would do the same job.
Upvotes: 1