Ver Mensaje Individual
  #3 (permalink)  
Antiguo 27/09/2012, 14:21
Avatar de akpshiva
akpshiva
 
Fecha de Ingreso: septiembre-2012
Mensajes: 16
Antigüedad: 11 años, 7 meses
Puntos: 0
Pregunta Respuesta: Colocar coordenadas de geolocalizacion dentro de un campo de un formulario

Hola Dradi7 gracias por su respuesta, cargué los datos de su sugerencia pero no me funciona y no me sale el mapa, me consegui otro ejemplo con codigo mas limpio, lo tengo publicado en la URL http://www.colombiainteligente.com/geolocalizacion/geolocalizacion.php y va conectado con un archivo geolocalizacion.js que contiene todo el codigo de geolocalizacion, lo que necesito es tomar los valores numericos de latitud y longitud y poder imprimirlos en los campos del formulario de latitud y longitud cuando me ubique la posición de tal forma que pueda guardarlos a través del formulario, creo que por este lado puede ser mas facil, estoy investigando algo sobre el uso de innerHTML pero no doy con la solucion todavia, si me puede dar una mano le agradezco.

Codigo de geolocalizacion.js

Código HTML:
//funcion autoejecutable para obtener las coordenadas con HTML Geolocation API
//y tambien dibujar un mapa utilizando el API de Google Maps
(function(){
	//capa que va a contener el mapa (esta definida en el documento HTML)
	var divMapa=document.getElementById('divMapa');
	//capa para mostrar las coordenadas (definida tambien en el HTML)
	var divCoordenadas=document.getElementById('divCoordenadas');
	
	//verificamos si el navegador soporta Geolocation API de HTML5
	if(navigator.geolocation){
		//intentamos obtener las coordenadas del usuario
		navigator.geolocation.getCurrentPosition(function(objPosicion){
			//almacenamos en variables la longitud y latitud
			var iLongitud=objPosicion.coords.longitude, iLatitud=objPosicion.coords.latitude;
			//mostramos en pantalla (solo texto) las coordenadas obtenidas
			divCoordenadas.innerHTML='Latitud: '+iLatitud+' - Longitud: '+iLongitud;
				
			//creamos un objeto (para Google Maps) con las coordenadas obtenidas por el API de HTML5
			var objCoordenadas=new google.maps.LatLng(iLatitud,iLongitud);
			
			//opciones del mapa
			var objOpciones={
				mapTypeId:		google.maps.MapTypeId.ROADMAP,	//mapa de carretera
				zoom: 			16,								//acercamiento
				mapTypeControl:	true,							//mostrar controles para cambiar el tipo de mapa
				center: 		objCoordenadas					//centramos el mapa en las coordenadas obtenidas
			};
			
			//dibujamos el mapa de la ubicacion (en la capa divMapa)
			var objMapa=new google.maps.Map(divMapa,objOpciones);
			//agregamos un marcador al mapa con nuestra ubicacion
			var objPunto=new google.maps.Marker({
				title:		'Ubicación Encontrada',	//agregamos un tooltip al punto
				position:	objCoordenadas,						//indicamos las coordenadas del punto
				map:		objMapa								//este es el mapa que anteriormente creamos
			});
		},function(objError){
			//manejamos los errores devueltos por Geolocation API
			switch(objError.code){
				//no se pudo obtener la informacion de la ubicacion
				case objError.POSITION_UNAVAILABLE:
					divMapa.innerHTML='La información de su posición no está disponible.';
				break;
				//timeout al intentar obtener las coordenadas
				case objError.TIMEOUT:
					divMapa.innerHTML='Tiempo de espera agotado.';
				break;
				//el usuario no desea mostrar la ubicacion
				case objError.PERMISSION_DENIED:
					divMapa.innerHTML='Acceso denegado.';
				break;
				//errores desconocidos
				case objError.UNKNOWN_ERROR:
					divMapa.innerHTML='Error desconocido.';
				break;
			}
		});
	}else{
		//el navegador del usuario no soporta el API de Geolocalizacion de HTML5
		divCoordenadas.innerHTML='Su navegador no soporta Geolocation API de HTML5';
	}
})();

Codigo de geolocalizacion.php

Código HTML:
<?php require_once('Connections/geolocalizacion.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO markers (name, address, lat, lng, type) VALUES (%s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['name'], "text"),
                       GetSQLValueString($_POST['address'], "text"),
                       GetSQLValueString($_POST['lat'], "double"),
                       GetSQLValueString($_POST['lng'], "double"),
                       GetSQLValueString($_POST['type'], "text"));

  mysql_select_db($database_geolocalizacion, $geolocalizacion);
  $Result1 = mysql_query($insertSQL, $geolocalizacion) or die(mysql_error());

  $insertGoTo = "registro_geo.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}
?>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Geolocation</title>
		<link rel="stylesheet" type="text/css" href="css/geolocation.css">
	</head>
	<body>
		<div id="divContenedor">
			<div id="divInfo">Georeferenciación de Ubicación</div>
			<div id="divMapa"></div>
			<div id="divCoordenadas"></div>
		</div>
        <table width="320" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td bgcolor="#D1D1BA">&nbsp;</td>
        </tr>
        <tr>
        <td bgcolor="#D1D1BA">&nbsp;
          <form method="post" name="form1" action="<?php echo $editFormAction; ?>">
            <table align="center" cellpadding="0" cellspacing="5">
              <tr valign="baseline">
                <td nowrap align="right">Nombre:</td>
                <td><input name="name" type="text" value="Jorge Diaz" size="32" readonly="readonly"></td>
              </tr>
              <tr valign="baseline">
                <td nowrap align="right">Dirección:</td>
                <td><input type="text" name="address" value="" size="32"></td>
              </tr>
              <tr valign="baseline">
                <td nowrap align="right">Latitud:</td>
                <td><input name="lat" type="text" value="" size="32"></td>
              </tr>
              <tr valign="baseline">
                <td nowrap align="right">Longitud:</td>
                <td><input type="text" name="lng" value="" size="32"></td>
              </tr>
              <tr valign="baseline">
                <td nowrap align="right">Tipo:</td>
                <td><select name="type" class="texto_formulario" id="type">
                  <option value="Opcion 1" selected="selected">Opcion 1</option>
                  <option value="Opcion 2">Opcion 2</option>
                  <option value="Opcion 3">Opcion 3</option>
                </select></td>
              </tr>
              <tr valign="baseline">
                <td nowrap align="right">&nbsp;</td>
                <td><input type="submit" value="Guardar Ubicación"></td>
              </tr>
            </table>
            <input type="hidden" name="MM_insert" value="form1">
          </form>
          <p>&nbsp;</p></td>
        </tr>
        </table>
        

		<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
		<script type="text/javascript" src="js/geolocation.js"></script>
	</body>
</html>