Search results
Top results related to glenview illinois google map directions from current location api
Top Answer
Answered Mar 25, 2017 · 6 votes
I have solved this. The problem was the line,
destination: marker.getPosition(),-
was not correct. This was giving me the coordinates of my current location and not the marker clicked.
I set the latit and longit in the function that sets the infoWindow, which have been defined as a global variable,
// Allow each marker to have an info window google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infoWindow.setContent(infoWindowContent[i][0]); infoWindow.open(map, marker); latit = marker.getPosition().lat(); longit = marker.getPosition().lng(); // console.log("lat: " + latit); // console.log("lng: " + longit); } })(marker, i));-
Then these are set to the destination,
marker.addListener('click', function() { directionsService.route({ // origin: document.getElementById('start').value, origin: myLatLng,- // destination: marker.getPosition(), destination: { lat: latit, lng: longit }, travelMode: 'DRIVING' }, function(response, status) { if (status === 'OK') { directionsDisplay.setDirections(response); } else { window.alert('Directions request failed due to ' + status); } });- });-
The full code is here on github.
A gh-pages working example.
1/5
Top Answer
Answered Jul 26, 2013 · 2 votes
Here's an update of your existing code:
// Executes in UI thread, after the parsing process@Overrideprotected void onPostExecute(List<List<HashMap<String, String>>> result) { if (result.size() < 1) { Toast.makeText(getActivity(), "No Points", Toast.LENGTH_SHORT).show(); return; } TextView tv1 = (TextView) getActivity().findViewById(R.id.location1); TextView tv2 = (TextView) getActivity().findViewById(R.id.location2); TextView tv3 = (TextView) getActivity().findViewById(R.id.location3); TextView tv4 = (TextView) getActivity().findViewById(R.id.location4); TextView[] views = {tv1, tv2, tv3, tv4}; // Traversing through all the routes for (int i = 0; i < result.size(); i++) { // Fetching i-th route List<HashMap<String, String>> path = result.get(i); String distance = "No distance"; // Fetching all the points in i-th route for (int j = 0; j < path.size(); j++) { HashMap<String, String> point = path.get(j); if (j == 0) { distance = point.get("distance"); continue; } } // Set text views[i].setText(distance); }}
This code makes a not-so-good assumption: It assumes that the size of result is the same size as views, which in your case should be 4. When you run this code, you may get an IndexOutOfBounds error if you have more than 4 results (which shouldn't happen). Eventually you will want to verify that the size of result is 4, or the number of TextView's you have. If you have any questions or this doesn't work right, just let me know :)
EDIT: To get all distances at once, you can modify your DownloadTask to take in multiple URL's.
Change class definition:
private class DownloadTask extends AsyncTask<String, Void, ArrayList<String>>-
This says that your background operation will return a list of String's.
Modified doInBackground(), which now can process multiple URL's:
// Downloading data in non-ui thread@Overrideprotected ArrayList<String> doInBackground(String... urlList) { try { ArrayList<String> returnList = new ArrayList<String>(); for(String url : urlList) { // Fetching the data from web service String data = Locations.this.downloadUrl(url); returnList.add(data); } return returnList; } catch (Exception e) { Log.d("Background Task", e.toString()); return null; // Failed, return null }}
Then you onPostExecute() becomes
// Executes in UI thread, after the execution of// doInBackground()@Overrideprotected void onPostExecute(ArrayList<String> results) { super.onPostExecute(results); ParserTask parserTask = new ParserTask(); // Invokes the thread for parsing the JSON data parserTask.execute(results);}
Now, you will have to modify your ParserTask code to take in a list of JSON Strings, and not just one JSON String. Just change your ParserTask input parameters and put everything inside a for loop to loop through each JSON String. You will also have to modify the parameter of onPostExecute() to take in a List of whatever is there already, so that way it doesn't process one result, but a list of results. I can't show you those modifications here because it would be way too long, and then there would be no challenge for you :)
EDIT TWO: In getLastLocation() you're only calling DownloadTask with one URL, but you should put four URL's like this downloadTask.execute(url1, url2, url3, url4). Also, since ParserTask still only processes one JSON String, you should take out the four TextView's and the array looping out of the onPostExecute(). To tell the ParserTask which TextView to populate, add a constructor to ParserTask which takes in a TextView as a parameter. Then make an instance variable within ParserTaskthat is assigned in the constructor and used in onPostExecute() to display the distance.
Then, take that TextView array stuff I gave you before and put it in the onPostExecute() of DownloadTask. When you loop through the String results, also loop through the TextView array and pass in the TextView in the ParserTask constructor.
Basically, you're adding a constructor in the ParserTask to tell it which TextView to draw on. When your DownloadTask is finished, you pass it the right TextView for the URL. For example, R.id.location3 for the third URL.
2/5
Top Answer
Answered Feb 25, 2014 · 1 votes
If you just move set_markers() to the end of success callback of getCurrentPosition() and user refuse to share his location, you won't get the map but just gray area. There is no center set for your map which is required property. Better to define it like:
var myOptions = { zoom: 10, center: new google.maps.LatLng(37.339386, -121.894955), mapTypeControl: true, navigationControl: true,}map = new google.maps.Map(document.getElementById("map"), myOptions);...
Additionally, you can also call set_markers() at the end of error callback of getCurrentPosition(), so in case that user refuse sharing of his location, you can show available locations:
// Get current location based on the IP Addressfunction set_current_location() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (position) { /* var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); var myLat = position.coords.latitude; var myLong = position.coords.longitude; */ add_location('My location', position.coords.latitude, position.coords.longitude); set_markers(new google.maps.LatLngBounds(), map); }, function error(err) { console.log('error: ' + err.message); set_markers(new google.maps.LatLngBounds(), map); }); } else { alert("Geolocation is not supported by this browser."); }}
See example at jsbin
3/5
Top Answer
Answered Feb 03, 2019 · 0 votes
I'm not sure what the issue was that was preventing you from realising your goals - I tried the code above and it appeared to work - as it was too cold to work in the garage I had a little play and created a small demo; perhaps though you or someone else might find the following useful?
Initially when the call to navigator.getCurrentLocation resolves with the user's location the map loads using the returned position object to form the map centre location. The route to the pre-defined destination is then calculated using the Directions service with a modified options parameter - notably in this instance to hide the default markers. The reason for hiding the markers is because they do not expose any events and thus we cannot bind any listeners to them so we add our own. The added markers allow the route to be dynamically re-calculated ( can also drag the actual route itself )
The text version of the directions is available by clicking on one of the two markers.
The destination is in Birmingham, UK. If you are outwith the UK this might not work immediately without editing this location. Also, a valid API key is required.
<!DOCTYPE html><html> <head> <title>Google Maps: Directions from my location to...</title> <meta charset='utf-8' /> <style> body, html { height:100%;margin:0;padding:0;box-sizing:border-box; } #map { width:100%;height:100vh; margin:auto;float:none; } #info{ display:none;padding:0.25rem;margin:1rem;background:white;font-size:0.75rem!important; } </style> <script> let map; let marker; let infoWindow; let oDir; let oTraf; let oDisp; let oReq; let destination={ lat:52.477068, lng:-1.911663 }; const modes={ walk:'WALKING', bike:'BICYCLING', car:'DRIVING', pub:'TRANSIT' }; const advReqOptions={ provideRouteAlternatives:true, optimizeWaypoints:true, avoidFerries:true, avoidHighways:false, avoidTolls:false }; function initMap(){ /* utility to add a new marker and assign listeners to it */ const addmarker=function( pos, type, colour ){ marker=new google.maps.Marker({ icon:'//maps.google.com/mapfiles/ms/icons/'+colour+'-pushpin.png', type:type, draggable:true, position:pos, map:map }); google.maps.event.addListener( marker, 'click', function(e){ infoWindow.getContent().style.display='block'; infoWindow.setPosition( this.getPosition() ); infoWindow.open( map ); }); google.maps.event.addListener( marker, 'dragend', calculateroute ); }; /* callback function when markers are dragged and the route is re-calculated */ const calculateroute=function(e){ oReq={ origin:this.type=='start' ? e.latLng : oReq.origin, destination:this.type=='finish' ? e.latLng : oReq.destination, travelMode:modes.car }; oDir.route( Object.assign( oReq, advReqOptions ), callback ); }; /* process the route response */ const callback=function(r,s){ if( s === 'OK' ) oDisp.setDirections( r ); else evtGeoFailure( s ); } /* Main callback invoked when the user's location has been identified */ const evtGeoSuccess=function(p){ /* create the map */ let location={ lat: parseFloat( p.coords.latitude ), lng: parseFloat( p.coords.longitude ) }; let options= { zoom: 16, center:location, mapTypeId: google.maps.MapTypeId.ROADMAP }; let routeoptions={ suppressMarkers:true, draggable:true, map:map }; /* create the map object */ map = new google.maps.Map( document.getElementById('map'), options ); /* add draggable markers to the start and end of pre-defined route */ addmarker( location, 'start', 'grn' ); addmarker( destination, 'finish', 'red' ); /* display the textual directions in an infowindow which opens on marker click */ infoWindow = new google.maps.InfoWindow({ maxWidth:450, disableAutoPan:false }); infoWindow.setContent( document.getElementById('info') ); /* create the objects required for the directions calculations */ oDir=new google.maps.DirectionsService(); oDisp=new google.maps.DirectionsRenderer( routeoptions ); oTraf=new google.maps.TrafficLayer(); /* construct the initial request */ oReq={ origin:location, destination:destination, travelMode:modes.car }; /* go get the directions... */ oDisp.setMap( map ); oTraf.setMap( map ); oDisp.setPanel( infoWindow.getContent() ); oDir.route( Object.assign( oReq, advReqOptions ), callback ); }; const evtGeoFailure=function(e){ console.info( 'you broke the internets: %s', e ) }; const config={ maximumAge:60000, timeout:5000, enableHighAccuracy:true }; if( navigator.geolocation ) navigator.geolocation.getCurrentPosition( evtGeoSuccess, evtGeoFailure, config ); } </script> <script src='//maps.googleapis.com/maps/api/js?key=<<APIKEY>>&callback=initMap' async defer></script> </head> <body> <div id='map'></div> <div id='info'></div> </body></html>
4/5
Top Answer
Answered May 20, 2017 · 2 votes
You will need an API Key in order to make the Google Map Live on your Project. You can get a API Key from here:
https://developers.google.com/maps/documentation/javascript/get-api-key
On your JavaScript part, remove the first Google Map Reference.
Add a JavaScript Code to Initialize your Map first at the beginning of the JavaScript Code.
<script> var map; function initMap() { map = new google.maps.Map(document.getElementById('DivMap'), { center: {lat: -34.397, lng: 150.644}, zoom: 8 }); }</script>
And on the Second Google Map Reference, change your code as following:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap&key=YOUR_API_KEY"></script>-
Change YOUR_API_KEY with the API Key you got.
This will enable your map and you can do your desired thing.
5/5
developers.google.com › directions › get-directionsGetting directions through the Directions API | Google for ...
developers.google.com › directions › get-directionsSpecify origins, destinations, and waypoints as text strings (e.g. "Chicago, IL" or "Darwin, NT, Australia"), as place IDs, or as latitude/longitude coordinates. The API returns the most...
developers.google.com › directions › supportSupport Options for Directions API | Google for Developers
developers.google.com › directions › supportMay 9, 2024 · Visit the Google Maps Platform Support Create a Case page in the Cloud Console. Alternatively, you can click the 'Create Case' button at the top of the Google Maps Platform Support page. Select the project related to your question in the top dropdown bar of the Cloud Console. Fill out the form in detail. Once your case is created, you can ...
stackoverflow.com › questions › 54498371How to request directions from current location to ...
stackoverflow.com › questions › 54498371Feb 2, 2019 · var directionsService = new google.maps.DirectionsService(); var directionsDisplay = new google.maps.DirectionsRenderer(); var trafficLayer = new google.maps.TrafficLayer(); var myLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); var LA = new google.maps.LatLng(34.0522, -118.2437);
www.mapquest.com › directions › toDirections to Glenview, IL - MapQuest
www.mapquest.com › directions › toDriving directions to Glenview, IL including road conditions, live traffic updates, and reviews of local businesses along the way.
www.maphill.com › united-states › illinoisGlenview, Cook County, Illinois, United States: Maps - Maphill
www.maphill.com › united-states › illinoisGraphic maps of the area around 42° 9' 30" N, 87° 28' 29" W. Each angle of view and every map style has its own advantage. Maphill lets you look at Glenview, Cook County, Illinois, United States from many different perspectives. Start by choosing the type of map. You will be able to select the map style in the very next step.
en.wikipedia.org › wiki › Glenview,_IllinoisGlenview, Illinois - Wikipedia
en.wikipedia.org › wiki › Glenview,_IllinoisCoordinates: 42°4′46″N 87°48′56″W. Glenview is an incorporated village located in Cook County, Illinois, United States, approximately 15 miles northwest of the Chicago Loop. Per the 2020 census, the population was 48,705. [4] . The current Village President is Michael Jenny. Geography.
Searches related to glenview illinois google map directions from current location api