How to create routes using google maps and PHP?

Asked

Viewed 841 times

-1

Hello, I am learning to use google maps and wanted to trace routes between a location saved in the database and the location of who enter the page(get customer’s address), can anyone help me? Currently I already have the code that allows to create points on the map through BD. The filenames are: config.php implementacao.php geo.php

DATABASE USED:

CREATE DATABASE DB_MARCADORES CREATE TABLE TB_MARCAS ( MARC_CODIGO INT NOT NULL AUTO_INCREMENT PRIMARY KEY , MARC_NOME VARCHAR( 60 ) NOT NULL , MARC_ENDERECO VARCHAR( 80 ) NOT NULL , MARC_LATITUDE FLOAT( 10, 6 ) NOT NULL , MARC_LONGITUDE FLOAT( 10, 6 ) NOT NULL , MARC_TIPO VARCHAR( 30 ) NOT NULL ) ENGINE = MYISAM ;

NOTE: the format of the address follows the pattern: N° of the house Street Name of the Street

<?php

$endereco="localhost";
$usuario="root";
$senha="usbw";
$banco="DB_MARCADORES";

$MySQLi=new mysqli($endereco,$usuario,$senha,$banco,3307);
	if(mysqli_connect_errno()){
		die(mysqli_connect_error());
		exit();
	}
	mysqli_set_charset($MySQLi,"utf8");

	session_start();
?>

<?php
require("config.php");

function parseToXML($htmlStr){
	$xmlStr=str_replace('<','&lt;',$htmlStr);
	$xmlStr=str_replace('>','&gt;',$xmlStr);
	$xmlStr=str_replace('"','&quot;',$xmlStr);
	$xmlStr=str_replace("'",'&#39;',$xmlStr);
	$xmlStr=str_replace("&",'&amp;',$xmlStr);
	return $xmlStr;
}

// Select all the rows in the markers table
$result_markers = "SELECT * FROM TB_MARCAS";
$resultado_markers = mysqli_query($MySQLi, $result_markers);

header("Content-type: text/xml");

// Start XML file, echo parent node
echo '<markers>';

// Iterate through the rows, printing XML nodes for each
while ($row_markers = mysqli_fetch_assoc($resultado_markers)){
  // Add to XML document node
  echo '<marker ';
  echo 'name="' . parseToXML($row_markers['MARC_NOME']) . '" ';
  echo 'address="' . parseToXML($row_markers['MARC_ENDERECO']) . '" ';
  echo 'lat="' . $row_markers['MARC_LATITUDE'] . '" ';
  echo 'lng="' . $row_markers['MARC_LONGITUDE'] . '" ';
  echo 'type="' . $row_markers['MARC_TIPO'] . '" ';
  echo '/>';
}

// End XML file
echo '</markers>';

 
  
  <div id="map"></div>
						
		
	<script>
	  var customLabel = {
      restaurant: {
        label: 'R'
      },
      bar: {
        label: 'B'
      }
    };

    function initMap() {
      var map = new google.maps.Map(document.getElementById('map'), {
        center: new google.maps.LatLng(-11.371964, -59.239523),
        zoom: 3
      });
      var infoWindow = new google.maps.InfoWindow;

      // Change this depending on the name of your PHP or XML file
      downloadUrl('implementacao.php', function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName('marker');
        Array.prototype.forEach.call(markers, function(markerElem) {
          var name = markerElem.getAttribute('name');
          var address = markerElem.getAttribute('address');
          var type = markerElem.getAttribute('type');
          var point = new google.maps.LatLng(
              parseFloat(markerElem.getAttribute('lat')),
              parseFloat(markerElem.getAttribute('lng')));

          var infowincontent = document.createElement('div');
          var strong = document.createElement('strong');
          strong.textContent = name
          infowincontent.appendChild(strong);
          infowincontent.appendChild(document.createElement('br'));

          var text = document.createElement('text');
          text.textContent = address
          infowincontent.appendChild(text);
          var icon = customLabel[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            label: icon.label
          });
          marker.addListener('click', function() {
            infoWindow.setContent(infowincontent);
            infoWindow.open(map, marker);
          });
        });
      });
    }
    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;

      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          request.onreadystatechange = doNothing;
          callback(request, request.status);
        }
      };
      request.open('GET', url, true);
      request.send(null);
    }

    function doNothing(){}
      
      
  </script>
 

1 answer

0

Assuming you have the coordinates of origin and destination in hand, the easiest way to do it would be as follows:

https://maps.google.com/maps?saddr=<coordenadas_origem>&daddr=Mcoordenadas destino>&output=embed

The variable "saddr" receives latitude and longitude separated by comma. The variable "daddr" receives the coordinates of the destination.

Here is a small example:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Rota entre dois pontos</title>
  </head>
  <body>
    <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <div style="padding: 10px 0 0; clear: both">
      <iframe width="750" scrolling="no" height="350" frameborder="0" id="map" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?saddr=-23.5496447,-46.6339021&daddr=-23.5570003,-46.6612482&output=embed"></iframe>
    </div>
</html>

Here are other examples that may be useful:

https://stackoverflow.com/questions/3217068/is-there-a-way-to-pass-arguments-to-google-maps-get-directions-functionality

https://cbsa.com.br/post/distancia-entre-cidades---google-maps-javascript-api-v3.aspx

Browser other questions tagged

You are not signed in. Login or sign up in order to post.