Insert points into a map with an array that passes through the database

Asked

Viewed 812 times

4

I’m creating a site where I need a map, and users fill in forms with latitude and longitude to create a point on that same map. Everything is stored in the database but I needed the name of the point, the latitude and the longitude to pass before in an array. That is, data saved in a database but always running in the array. My code is this::

<html>
<?php include("header.php");?>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Google Maps </title>
 <script src="http://maps.google.com/maps/api/js?key=AIzaSyDTXwZGf67oO-63Ci_OfR7CzB7Wm003Gow&sensor=false"
            type="text/javascript"></script>
</head>
<body>
<div class="content">

<h1><b>Roteiro Definido</b></h1>
<hr/>
<div style="float: left;">
<h2><b>Indicações</b></h2>
  <dl>
    <dt><b>Nome do Local</b></dt>
    <dd>-------------</dd>

    <dt><b>Tipo de Local</b></dt>
    <dd>-------------</dd>

    <dt><b>Moradado Local</b></dt>
    <dd>---------------</dd>

    <dt><b>Código Postal e Localidade</b></dt>
    <dd>--------------------------</dd>
  </dl></div>



    <div id="map" style="width: 500px; height: 400px; float: right;"></div>

    <script type="text/javascript">
        var locations = [

          ['Parque estacionamento', 41.69114219999999, -8.828242600000067, 3],
          ['Praia do Norte', 41.696997, -8.850979000000052, 2],
          ['Navio Gil Eanes', 41.69009, -8.830255999999963, 1]
        ];

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 10,
            center: new google.maps.LatLng(41.694808, -8.830981),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        var infowindow = new google.maps.InfoWindow();

        var marker, i;

        for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                map: map
            });

            google.maps.event.addListener(marker, 'click', (function (marker, i) {
                return function () {
                    infowindow.setContent(locations[i][0]);
                    infowindow.open(map, marker);
                }
            })(marker, i));
        }
    </script>
</body>
</html>
 </div>
<?php include("footer.php");?>
  • You made the ajax to return this data ?

  • You should use ajax for that Melissa

  • @Diegosouza Good afternoon, no, I’ll leave the whole code to see, I’ll edit the question

  • @Miguel Abe show me how to do it? I’ve never used ajax

  • I’ll try to help

2 answers

2


You have to create an ajax function that does the query in the database.

var request = new XMLHttpRequest();
request.open('GET', '/localizacoes.php', true);

request.onload = function(){
  if (request.status >= 200 && request.status < 400) {
    var data = request.responseText;

    criarMapa(data);
  } 
  else{
    console.log('Deu erro!');
  }
};

request.onerror = function() {
  console.log('Deu erro!');
};

request.send();

function criarMapa(locations){

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10,
        center: new google.maps.LatLng(41.694808, -8.830981),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
        });

        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infowindow.setContent(locations[i][0]);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }
}

You have to create a page PHP for you to select and send this data.

I named it after localizacoes.php in the method parameter open(). But you can choose another name for your page.

Then you just make the query and return the array. But the data is inside another array.

$query   = "SELECT nome, latitude, longitude FROM pontos";
$execute = mysqli_query($conn, $query);
$result  = mysqli_fetch_array($execute);

$arrMaps [];

foreach($result as $key => $item){
    $arrMaps($arrMaps, [$item->nome, $item->latitude, $item->longitude, $key]);
}

return $arrMaps;

It’s just an idea, maybe something goes wrong.

  • I’ll try it, thank you very much

1

You can do so on the client side, dynamically add a zone to your map, by default you already have an area in the input ready to test, not far from the locations you already have there (PS: Always nice to see someone from Portugal here, welcome):

var locations = [
      ['Parque estacionamento', 41.69114219999999, -8.828242600000067],
      ['Praia do Norte', 41.696997, -8.850979000000052],
      ['Navio Gil Eanes', 41.69009, -8.830255999999963]
    ];

function init_map(locations) {

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10,
        center: new google.maps.LatLng(41.611751, -8.785640),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
        });

        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infowindow.setContent(locations[i][0]);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }
  }

init_map(locations);

$('#add').on('click', function() {
  var zona = $('#zona').val();
  var newCoords = $('#coords').val().split(',');
  newCoords.unshift(zona);
  locations.push(newCoords);
  init_map(locations);
  // aqui colocas o teu ajax e envias para o servidor as novas coordenadas e zona: newCoords
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.google.com/maps/api/js?&sensor=false"
        type="text/javascript"></script>

Nome da Zona<input type="text" id="zona">
<br>
Coord<input id="coords" placeholder="41.682451, -8.794165" value="41.682451, -8.794165" type="text" id="coords">
<button id="add">Add<button>
<div id="map" style="width: 500px; height: 400px; float: right;"></div>

  • But how do I get it from the database? is that in this case the array will run with the values that the user puts, and so everything goes to a BD

  • Ha I understand you want other users to see what an inserts @Melissasousa?

  • yes, if you can help me

  • This is an ajax request within a setInterval() .. I now don’t have time to demonstrate maybe this weekend I can help. But basically it is an ajax request of 1sec in 1sec (for example), to "ask" to the server if there are new locations, if there is, the server sends them in response to this request, and then there yes, enters the part I made in the click, that is to be in the success of the ajax function: http://stackoverflow.com/questions/9436534/ajax-tutorial-for-post-and-get here’s an example @Melissasousa

Browser other questions tagged

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