Link to home
Start Free TrialLog in
Avatar of IT student
IT student

asked on

display location from my current location to another selected location

I am trying to implement a map/direction based application using Google maps V3 API. So far I have been able to display the map and show directions for two locations selected. the first one is my current location , the second one is the location of costumer (his/her information exist in my database). All the markers are being displayed in the output properly.

you'll see that in the form select box is automatically detect user's location, Also, i add a panel in which to display directions.

the Destination field show to us the code client (code client is the code of costumers , it's a number ) so when we select the code client from the destination field it take the Geoaddress of this costumer (the owner of this code client) and it desplay location to it in the map from our location.

PS0 :
sorry about my english language , i try to explain good for you even i don't speak good english language

PS1 : code client and Geosddress and longitude and latitude ... all information in my database

PS2 : the code client is the code of costumer

information about the code

First, i create new objects before the init function - DirectionsService and DirectionsRenderer. and i configure the directionsDisplay object. i did it inside init function. Also, i add autodetection of user's location to init function.

i use W3C Geolocation. If the geolocation succeds we use Geocoding to get the user's address. If this succeds we enter that location to the location text box.

i also added the addOption function which adds options to a select box. So, inside our for loop we call the addOption function with selectbox, CodeClient and GeoAdresse parameters. First parameter indicates which selectbox to fill.

Next,i add a calculateRoute function inside our JavaScript This function is pretty simple. It uses text from input field as a origin address and selected location as a destination. If the field is empty, we'll use city center as a starting point. We then use route method to issue a request to the Directions service. If status is OK, we display directions.

issue

i want that instead of using the Geo Address as a destination , it will use the longitude and latitude of the customer as an destination . because when it use the Geoaddres as a destination it not take us exactly to the customer selected by code client so it's not specific to an exact customer i mean the Geo Address can be the same for lot of customer ,so instead of using the geoaddress of customer i want to use longitude and latitude as destination reference to be more specified in the location of destination because as you know the longitude and latitude are more specific

if you need any more information , just ask me .

PS3 : in the code snippet that i made for you it display an message " Geolocation is supported, but it failed " i don't know why but it work good in my computer , it's just a simple error . any one can manipulate the code , i will be thankful

CSS code

body { font: normal 14px Verdana; }
h1 { font-size: 24px; }
h2 { font-size: 18px; }
#sidebar { float: right; width: 30%; }
#main { padding-right: 15px; }
.infoWindow { width: 220px; }

Open in new window



html code

<title>MAP itinéraire </title>
<meta charset="utf-8">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>

    <body onload="init();">
          
		
		
		    <form id="services">
				Location: <input type="text" id="start" />
				Destination: <select id="destination" onchange="calculateRoute();"></select>
				<input type="button" value="afficher la direction" onclick="calculateRoute();" />
			</form>
		
        <section id="sidebar">
            <div id="directions_panel"></div>
        </section>
          
        <section id="main">
            <div id="map_canvas" style="width: 70%; height: 750px;"></div>
        </section>
          
    </body>

Open in new window



JS code


        var map;
		
		var directionsService = new google.maps.DirectionsService();
		var directionsDisplay = new google.maps.DirectionsRenderer();
		
	
		
		var geocoder = new google.maps.Geocoder();
		var infowindow = new google.maps.InfoWindow();
          
        function init() {
              
            var mapOptions = {
                zoom: 6,
                center: center = new google.maps.LatLng(32,-6),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
              
            map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
			
			
			
			    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById('directions_panel'));
      
    // Detect user location
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
              
            var userLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
              
            geocoder.geocode( { 'latLng': userLocation }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    document.getElementById('start').value = results[0].formatted_address
                }
            });
              
        }, function() {
            alert('Geolocation is supported, but it failed');
        });
    }
			
			
			
			
			
    makeRequest('https://gist.githubusercontent.com/abdelhakimsalama/358669eda44d8d221bf58c629402c40b/raw/eca59a21899fe19b1f556ff033a33dff2a6bdd0c/get_data_google_api', function(data) {
          
        var data = JSON.parse(data.responseText);
        var selectBox = document.getElementById('destination');
          
        for (var i = 0; i < data.length; i++) {
            displayLocation(data[i]);
            addOption(selectBox, data[i]['CodeClient'], data[i]['GeoAdresse']);

			
        }
    });
	
        }
		
		
		function addOption(selectBox, text, value) 
		{
			var option = document.createElement("OPTION");
			option.text = text;
			option.value = value;
			selectBox.options.add(option);
		}
		
		
		
		
		function calculateRoute() 
		{
              
			var start = document.getElementById('start').value;
			var destination = document.getElementById('destination').value;
			  
			if (start == '') {
				start = center;
			}
			  
			var request = {
				origin: start,
				destination: destination,
				travelMode: google.maps.DirectionsTravelMode.DRIVING
			};
			directionsService.route(request, function(response, status) {
				if (status == google.maps.DirectionsStatus.OK) {
					directionsDisplay.setDirections(response);
				}
			});
		}
		
		
		
		
		function makeRequest(url, callback) 
		{
			var request;
			if (window.XMLHttpRequest) 
			{
				request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
			} 
			else 
			{
				request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
			}
				request.onreadystatechange = function() 
				{
					if (request.readyState == 4 && request.status == 200) 
						{
							callback(request);
						}
				}
			request.open("GET", url, true);
			request.send();
		}
		
			
		function displayLocation(rythmstu_innotec)
		{
          
				var content =   '<div class="infoWindow"><strong> Code Client : '  + rythmstu_innotec.CodeClient + '</strong>'
                    + '<br />Latitude : '     + rythmstu_innotec.Latitude
                    + '<br />Longitude : '     + rythmstu_innotec.Longitude 
					+ '<br />Route : '     + rythmstu_innotec.Route 
					+ '<br />Secteur : '     + rythmstu_innotec.Secteur  
					+ '<br />Agence : '     + rythmstu_innotec.Agence 
					+ '<br />prenom de Client : '     + rythmstu_innotec.PrenomClient 
					+ '<br />Num Adresse : '     + rythmstu_innotec.NumAdresse 
					+ '<br />GeoAdresse : '     + rythmstu_innotec.GeoAdresse 
					+ '<br />Téléphone : '     + rythmstu_innotec.Tel 
					+ '<br />Whatsapp : '     + rythmstu_innotec.Whatsapp 
					+ '<br />Nbr Frigos : '     + rythmstu_innotec.NbrFrigo
					+ '<br />Ouverture Matin : '     + rythmstu_innotec.OpenAm 
					+ '<br />Fermeture Matin : '     + rythmstu_innotec.CloseAm 
					+ '<br />Ouverture après-midi : '     + rythmstu_innotec.OpenPm 
					+ '<br />Fermeture Après-midi : '     + rythmstu_innotec.ClosePm + '</div>';
      
				if (parseInt(rythmstu_innotec.Latitude) == 0) 
				{
					geocoder.geocode( { 'GeoAdresse': rythmstu_innotec.GeoAdresse }, function(results, status) 
					{
						if (status == google.maps.GeocoderStatus.OK) 
						{
							var marker = new google.maps.Marker({
								map: map, 
								position: results[0].geometry.rythmstu_innotec,
								title: rythmstu_innotec.name
						});
                  
							google.maps.event.addListener(marker, 'click', function() 
							{
							infowindow.setContent(content);
							infowindow.open(map,marker);
							});
						}
					});
				} 
				else
				{
					var position = new google.maps.LatLng(parseFloat(rythmstu_innotec.Latitude), parseFloat(rythmstu_innotec.Longitude));
					var marker = new google.maps.Marker({
						map: map, 
						position: position,
						title: rythmstu_innotec.name
					});
          
						google.maps.event.addListener(marker, 'click', function() {
							infowindow.setContent(content);
							infowindow.open(map,marker);
						});
					}
}

Open in new window

Avatar of John Jonson
John Jonson

From your post, I understood that I will never be a good programmer, but I'm happy that at least I'm a good writer in https://essayvikings.com/ . Could you make a screen how the page will look after coding?
Really enjoyed this article post. Really looking forward to read more. Will read on...      
https://marvelous-reviews.com/
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.