InicioInfoUso de PHP / Postgis con Google Maps Marker
PHP / Postgis con Google Maps API

Es este post hablaremos de dibujar poligonos y marcadores con la api de google maps obteniendo la informacion de una base de datos.

CREANDO LA TABLA Y COMO POBLARLA CON DATOS

CREATE TABLE marker ( id SERIAL, estado character varying, municipio character varying, localidad character varying, geom geometry(Point,4326));

INSERT INTO marker VALUES (5, ' GUANAJUATO ', 'PENJAMO', 'ESTACION CORRALEJO', '0101000020E61000002A85E5747E5259C06F2F698CD6713440');
INSERT INTO marker VALUES (6, ' GUANAJUATO ', 'PENJAMO', 'VEREDAS', '0101000020E61000000A2E56D4607659C09129BC57EF413440');
INSERT INTO marker VALUES (7, ' GUANAJUATO ', 'HUANIMARO', 'LA LOBERA (EL RINON)', '0101000020E61000006F641EF9836259C07233DC80CF5B3440');
INSERT INTO marker VALUES (8, ' GUANAJUATO ', 'VALLE DE SANTIAGO', 'RINCON DE PARANGUEO', '0101000020E6100000A5BDC117265059C0E4D3C685C16B3440');
INSERT INTO marker VALUES (9, ' GUANAJUATO ', 'PENJAMO', 'SAN ANTONIO DE ACEVES', '0101000020E610000081711530A67C59C0EC84FA0A907F3440');
INSERT INTO marker VALUES (10, ' GUANAJUATO ', 'CUERAMARO', 'TUPATARO', '0101000020E61000001B7F47F96E6959C0AA8251499D983440');
INSERT INTO marker VALUES (11, ' GUANAJUATO ', 'PENJAMO', 'LAGUNA LARGA DE CORTES', '0101000020E6100000847A9F4F097C59C069A7499D3E653440');
INSERT INTO marker VALUES (12, ' GUANAJUATO ', 'PENJAMO', 'ESTACION PENJAMO', '0101000020E6100000BD6D4B89496C59C0EAEC647094643440');
INSERT INTO marker VALUES (13, ' GUANAJUATO ', 'SALAMANCA', 'LA CAPILLA', '0101000020E6100000CF6D1D77255359C06EF8409F868E3440');
INSERT INTO marker VALUES (14, ' GUANAJUATO ', 'IRAPUATO', 'SANTA ELENA DE LA CRUZ', '0101000020E6100000F1F44A59865959C091806EBB129E3440');
INSERT INTO marker VALUES (15, ' GUANAJUATO ', 'HUANIMARO', 'SAN JOSE DE AYALA', '0101000020E6100000B6BE4868CB5559C09B5C2957BA543440');
INSERT INTO marker VALUES (16, ' GUANAJUATO ', 'ABASOLO', 'SAN TELMO DE ROA', '0101000020E61000005A6B836E0A5F59C02D28A99F79763440');
INSERT INTO marker VALUES (17, ' GUANAJUATO ', 'HUANIMARO', 'LOS OTATES', '0101000020E610000070496991C85E59C04390831266663440');
INSERT INTO marker VALUES (18, ' GUANAJUATO ', 'VALLE DE SANTIAGO', 'LAS JICAMAS', '0101000020E6100000D7E48464DC5659C0C132999E6E473440');
INSERT INTO marker VALUES (19, ' GUANAJUATO ', 'PENJAMO', 'POTRERILLOS DEL RIO', '0101000020E6100000B9196EC0E77259C0061487BF68383440');
INSERT INTO marker VALUES (20, ' GUANAJUATO ', 'PUEBLO NUEVO', 'PROGRESO DE LA UNION', '0101000020E6100000A538A2D60F5759C0A8DCA75788913440');
INSERT INTO marker VALUES (21, ' GUANAJUATO ', 'PUEBLO NUEVO', 'YOSTIRO (YOSTIRO DE SAN ANTONIO)', '0101000020E6100000FCA2A943935959C01689A63F3D8F3440');
INSERT INTO marker VALUES (22, ' GUANAJUATO ', 'IRAPUATO', 'CUCHICUATO', '0101000020E61000006CEE4339AC5D59C0F02CA470FBA83440');
INSERT INTO marker VALUES (23, ' GUANAJUATO ', 'ABASOLO', 'LA CARROZA', '0101000020E6100000FE261422E06559C0E90E62670A913440');
INSERT INTO marker VALUES (24, ' GUANAJUATO ', 'CUERAMARO', 'CERRITO DE AGUA CALIENTE', '0101000020E610000008AC1C5A646559C0255FA67909A33440');

Este archivo nada mas carga la variables para abrir la base de datos.

ARCHIVO funciones.php
<?php
$db_crtgrf='gis_db';
$port='5432';
$host='localhost';
$usr='postgres';
$contrasena='pass_db';
?>

Archivo marcadores.php

<?php
require('../funciones.inc');
?>
<html>
<head>

Agregar la linea donde se carga la API de Google Maps.

[color=#000000][color=#000000][color=#000000][color=#000000]
 var customIcons = {
      restaurant: {
        icon: 'https://labs.google.com/ridefinder/images/mm_20_blue.png',
        shadow: 'https://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      bar: {
        icon: 'https://labs.google.com/ridefinder/images/mm_20_red.png',
        shadow: 'https://labs.google.com/ridefinder/images/mm_20_shadow.png'
      }
    };

 function load() {
      var map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(19.3957175,-99.0971625),
        zoom: 15,
        mapTypeId: 'roadmap'
      });
      
      var infoWindow = new google.maps.InfoWindow;
      var bounds = new google.maps.LatLngBounds();
        downloadUrl("marcador_map_genxml.php", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
          var address = markers[i].getAttribute("estado");
          var localidad = markers[i].getAttribute("localidad");
          var nombre_municipio = markers[i].getAttribute("municipio");
          var type = markers[i].getAttribute("type");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
              bounds.extend(point);
          var html = "<b>ESTADO :" + address + "</b> <br/>" +"<b>MUNICIPIO :" + nombre_municipio + "</b> <br/>"+"<b>LOCALIDAD :" + localidad + "</b>"  ;
          var icon = customIcons[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon,
            shadow: icon.shadow
          });
          bindInfoWindow(marker, map, infoWindow, html);
        }

if (typeof point == "undefined")
 { 
var point = new google.maps.LatLng(19.3957175,-99.0971625);
bounds.extend(point);
center = bounds.getCenter();
 } 
 else 
     {
  center = bounds.getCenter();
 map.fitBounds(bounds);
 }
      });
    }

   
    function bindInfoWindow(marker, map, infoWindow, html) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        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() {}

function limpiaDivs()
{
    document.getElementById("map").innerHTML="";
}


[/color][/color][/color][/color]



</head>
<body onload=load()>
<form name=distritos id=distritos>
<div class=container>
<table class='table table-responsive table-condensed'>
<tr><td class='text-center'>
<b><h4>MARCADORES</h4></b>
</td></tr>
</table>
<?php
echo "<div align=center name=txtHint id=txtHint></div>";
echo "<div name='map' id='map' style='width: 100%; height: 750px'></div>";
echo "</div>";
?>
</div>
</form>
</body>
</html>

Este archivo realiza la consulta a la base de datos y se genera el XML.

Archivo marcador_map_genxml.php



require("../funciones.inc";
require_once('lib/support_functions.php');
$db=pg_connect("dbname=$db_crtgrf port=$port host=$host user=$usr password=$contrasena";
if (!$db) { exit(pg_last_error($db)); }
$sql="SELECT estado, municipio, localidad, ST_ST_CENTROID(geom)) AS lon, ST_Y(ST_CENTROID(geom)) AS lat FROM marker";

$resultado=pg_query($db,$sql);
if (!$resultado) { exit(pg_last_error($resultado)); }

$filas=pg_num_rows($resultado);
$campos=pg_num_fields($resultado);


function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
// Opens a connection to a MySQL server
$connection=pg_connect("dbname=$db_crtgrf port=$port host=$host user=$usr password=$contrasena";
if (!$connection) { die('Not connected : ' . pg_last_error($connection)); }
$query = $sql;
//echo $query; exit;
$result = pg_query($connection,$query);
if (!$result) {
die('Invalid query: ' . pg_query_error($result));
}


header("Content-type: text/xml";
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @pg_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'estado="' . parseToXML($row['estado']) . '" ';
echo 'municipio="' . parseToXML($row['municipio']) . '" ';
echo 'localidad="' . parseToXML($row['localidad']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lon'] . '" ';
echo '/>';
}
echo '</markers>';

Archivo support_functios.php


Al final deberias ver algo parecido a esto.

Datos archivados del Taringa! original
19puntos
179visitas
0comentarios
Actividad nueva en Posteamelo
0puntos
3visitas
0comentarios
Dar puntos:

Dejá tu comentario

0/2000

Autor del Post

a
amatjal🇦🇷
Usuario
Puntos0
Posts6
Ver perfil →
PosteameloArchivo Histórico de Taringa! (2004-2017). Preservando la inteligencia colectiva de la internet hispanohablante.

CONTACTO

18 de Septiembre 455, Casilla 52

Chillán, Región de Ñuble, Chile

Solo correo postal

© 2026 Posteamelo.com. No afiliado con Taringa! ni sus sucesores.

Contenido preservado con fines históricos y culturales.