Jump to content

Recommended Posts

Posted

Boas,

Eu estou a criar uma página onde digo o local onde estou (Rua, Latitude e Longitude):

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Browser Geolocation Lookup, HTML 5 Geolocation API Demo</title>
<meta name="keywords" content="Browser Geolocation, HTML 5 Geolocation, Geoloation API">
<meta name="description" content="My Browser Geolocation, HTML 5 Geolocation API demo, Geolocation supports in popular browsers, Firefox Geolocation, Chrome Geolocation, Opera Gelocation, Safari Gelocation">
<meta name="verify-v1" content="z+SWi0YAVOqtldDp4vmjZernZdSl3OZI97/ZHT0a/DM=" >
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAA782cqum_5jUTcmf5HZOJ1hTjRJkYzsbZct0CfFBjnjyKW40ZohQ1pB9JIOh-XAPK3AYDBoEuuNNV2A" type="text/javascript"></script>
<script type="text/javascript">
var map;
var geocoder;
function addAddressToMap(response)
{
 map.clearOverlays();
 if (!response || response.Status.code != 200)
 {
  alert("Sorry, we were unable to geocode that address");
 }
 else
 {
  place = response.Placemark[0];
  point = new GLatLng(place.Point.coordinates[1],
    place.Point.coordinates[0]);
  marker = new GMarker(point);
  map.setCenter(point, 13);
  map.addOverlay(marker);
  document.getElementById('address').innerHTML = place.address;
 }
}

   function initialize()
{
 map = new GMap2(document.getElementById("map_image"));
 map.setCenter(new GLatLng(34, 0), 1);
 map.setUIToDefault();
 geocoder = new GClientGeocoder();
 if (navigator.geolocation)
 {
  navigator.geolocation.getCurrentPosition(function(position)
  { 
   document.getElementById('latitude').innerHTML = position.coords.latitude;
   document.getElementById('longitude').innerHTML = position.coords.longitude;
   var coord = position.coords.latitude+","+position.coords.longitude;
   geocoder.getLocations(coord, addAddressToMap);
  });
 }
}
</script>
</head>
<body onload="initialize()">
<center>
<table id="main-table">
<tr>
 <td colspan="2">
 <div id="header-left">
 <a title="browser download bookmark" href="http://www.addthis.com/bookmark.php?v=250&pub=xa-4a5152b36e027ce9" onmouseover="return addthis_open(this, '', '[url]', '[TITLE]')" onmouseout="addthis_close()" onclick="return addthis_sendto()"><img src="http://s7.addthis.com/static/btn/lg-bookmark-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js?pub=xa-4a5152b36e027ce9"></script>
 </div>
 <div id="header-right">
<form action="http://www.google.com/cse" id="cse-search-box" target="_blank">
 <div>
   <input type="hidden" name="cx" value="partner-pub-2478635682156982:z1ixf07l6ki" />
   <input type="hidden" name="ie" value="UTF-8" />
   <input type="text" name="q" size="31" value="best browser"/>
   <input type="submit" name="sa" value="Search" />
 </div>
</form>
<script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&lang=en"></script> 
 </div>
 </td>
</tr>
<tr>
 <td id="main-content">
 <h1 id="intro">Browser Geolocation API is a new feature introduced in <a href="http://www.w3.org/TR/geolocation-API/" target="_blank">HTML5</a>. Websites can get your location information from <a href="#browser-gelocation-support">browsers that support Geolocation API</a> to bring you better service. The below map shows your location information gathered by your browser.</h1>
 <h1 id="main-title">Your Browser Geolocation:</h1>
 <span class="coordinates-label">Latitude: </span><span class="coordinates" id="latitude"><img class="pic-loading" src="loading.gif" alt="Get Browser Geolocation">Loading...</span>
     
 <span class="coordinates-label">Longitude: </span><span class="coordinates" id="longitude"><img class="pic-loading" src="loading.gif" alt="Get Browser Geolocation">Loading...</span>
 <br>
 <span class="address-label">Address: </span>
 <span id="address"><img class="pic-loading" src="loading.gif" alt="Get Browser Geolocation">Loading...</span><br>


</tr>

</table>
</center>
</body>
</html>

Mas não me diz porque preciso de algo:

Este Web site necessita uma chave da API do Google Maps diferente. A nova chave pode ser gerada em http://code.google.com/apis/maps/documentation/javascript/v2/introduction.html#Obtaining_Key.

Alguem me pode ajudar?

Posted

Boa tarde,

Básicamente precisa de uma Key para a API google. A key que está a usar deve ser uma key de um exemplo.

<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAA782cqum_5jUTcmf5HZOJ1hTjRJkYzsbZct0CfFBjnjyKW40ZohQ1pB9JIOh-XAPK3AYDBoEuuNNV2A" type="text/javascript">
</script>

É trocar o valor de key pela nova chave.

Cordiais cumprimentos,

Apocsantos

"A paciência é uma das coisas que se aprendeu na era do 48k" O respeito é como a escrita de código, uma vez perdido, dificilmente se retoma o habito"

Posted

Boa tarde,

Básicamente precisa de uma Key para a API google. A key que está a usar deve ser uma key de um exemplo.

<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAA782cqum_5jUTcmf5HZOJ1hTjRJkYzsbZct0CfFBjnjyKW40ZohQ1pB9JIOh-XAPK3AYDBoEuuNNV2A" type="text/javascript">
</script>

É trocar o valor de key pela nova chave.

Cordiais cumprimentos,

Apocsantos

Eu tirei o source code deste website http://www.browsergeolocation.com/#browser-gelocation-support

e deu-me esse erro, se calhar falta algo que nao aparece no source.

Será que me pode ajudar? O meu objetivo é so a posicao (exemplo: Rua Capitao Ribeiro, Vila Nova de Gaia, Portugal), latitude e longitude, não quero o mapa...

Cumprimentos,

PF2G

Posted (edited)

Ok, consegui um codigo melhor, mas falta-me a posição.

A minha ideia é atraves da latitude e da longitude conseguir a rua onde estou.

<!DOCTYPE HTML>
<head>
<script type="text/javascript">
function showLocation(position) {
var geocoder;

var latitude = position.coords.latitude;
var longitude = position.coords.longitude;

   //Aqui fica o Address

document.write("Latitude : " + latitude + " <br/>Longitude: " + longitude);
}

function errorHandler(err) {
 if(err.code == 1) {
alert("Error: Access is denied!");
 }else if( err.code == 2) {
alert("Error: Position is unavailable!");
 }
}
function getLocation(){

  if(navigator.geolocation){
  // timeout at 60000 milliseconds (60 seconds)
  var options = {timeout:600000};
  navigator.geolocation.getCurrentPosition(showLocation,
										   errorHandler,
										   options);
  }else{
  alert("Sorry, browser does not support geolocation!");
  }
}
</script>
</head>
<html>
<body>
  <form>
 <input type="button" onclick="getLocation();"  
						 value="Get Location"/>
  </form>
</body>
</html>

Alguem me pode ajudar?

Edited by PF2G
Posted

1 dica:

A partir de agora (durante, pelo menos, 1 ano) esquece que "document.write" existe. Esquece! Este método é suposto só ser usado em situações muito específicas e não estás a ver quais são as situações. Mais tarde, talvez, irás saber. Sempre que vir que o problema que tens está diretamente ou indiretamente relacionado com "document.write" n vou ajudar-te a resolver. Precisas de te livrar das más práticas de programação.

Seguinte:

Vê isto:

http://stackoverflow.com/questions/4804495/google-maps-v3-snap-to-nearest-street

Tens aqui tudo o que precisas. Só falta alterar um pouco para adaptar à tua situação.

"[Os jovens da actual geração]não lêem porque não envolve um telecomando que dê para mirar e atirar, não falam porque a trapalhice é rainha e o calão é rei" autor: thoga31

Life is a genetically transmitted disease, induced by sex, with death rate of 100%.

Posted (edited)

1 dica:

A partir de agora (durante, pelo menos, 1 ano) esquece que "document.write" existe. Esquece! Este método é suposto só ser usado em situações muito específicas e não estás a ver quais são as situações. Mais tarde, talvez, irás saber. Sempre que vir que o problema que tens está diretamente ou indiretamente relacionado com "document.write" n vou ajudar-te a resolver. Precisas de te livrar das más práticas de programação.

Seguinte:

Vê isto:

http://stackoverflow.com/questions/4804495/google-maps-v3-snap-to-nearest-street

Tens aqui tudo o que precisas. Só falta alterar um pouco para adaptar à tua situação.

Consegui alterar a key e funciona na perfeição.

<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=AIzaSyA0j5IYhcF36pWJtGwGQpcI2UTtp6VSB88" type="text/javascript"></script>
<script type="text/javascript">
var map;
var geocoder;
function addAddressToMap(response)
{
 map.clearOverlays();
 if (!response || response.Status.code != 200)
 {
  alert("Sorry, we were unable to geocode that address");
 }
 else
 {
  place = response.Placemark[0];
  point = new GLatLng(place.Point.coordinates[3],
	place.Point.coordinates[0]);
  marker = new GMarker(point);
  map.setCenter(point, 13);
  map.addOverlay(marker);
  document.getElementById('address').innerHTML = place.address;
 }
}

function initialize()
{
 map = new GMap2(document.getElementById("map_image"));
 map.setCenter(new GLatLng(34, 0), 1);
 map.setUIToDefault();
 geocoder = new GClientGeocoder();
 if (navigator.geolocation)
 {
  navigator.geolocation.getCurrentPosition(function(position)
  {
document.getElementById('latitude').innerHTML = position.coords.latitude;
document.getElementById('longitude').innerHTML = position.coords.longitude;
var coord = position.coords.latitude+","+position.coords.longitude;
geocoder.getLocations(coord, addAddressToMap);
  });
 }
}
</script>

<span>LOCAL:</span>
	 <label>
	  <span id="address" style="margin-left:5px; width:500px; color:#000000; font-size:14px;"><img class="pic-loading" style="margin-left:5px;" src="loading.gif" alt="Get Browser Geolocation">Loading...</span>
	 </label>


	 <span style="display:none;" class="coordinates-label">Latitude: </span><span style="display:none;"  class="coordinates" id="latitude"><img class="pic-loading" src="loading.gif" alt="Get Browser Geolocation">Loading...</span>
	     
	 <span style="display:none;" class="coordinates-label">Longitude: </span><span style="display:none;"  class="coordinates" id="longitude"><img class="pic-loading" src="loading.gif" alt="Get Browser Geolocation">Loading...</span>
	 <div style="display:none;" id="map_image" style="width: 800px; height: 450px">
	 <!-- Google Maps Canvas-->
	 </div>
   <script type="text/javascript">
	if (!navigator.geolocation)
	{
	 document.getElementById('latitude').innerHTML = "Desconhecido";
	 document.getElementById('longitude').innerHTML = "Desconhecido";
	 document.getElementById('address').innerHTML = "Desconhecido";
	 alert("O seu browser não suporta os serviços.");
	}
   </script>

Só que agora quero ir buscar outra vez a localização e não consigo:

(2ª chamada da função)

<label>
		 <span id="address" style="margin-left:5px; width:500px; color:#000000; font-size:14px;"><img class="pic-loading" style="margin-left:5px;" src="loading.gif" alt="Get Browser Geolocation">Loading...</span>
		</label>


		<span style="display:none;" class="coordinates-label">Latitude: </span><span style="display:none;"  class="coordinates" id="latitude"><img class="pic-loading" src="loading.gif" alt="Get Browser Geolocation">Loading...</span>
		    
		<span style="display:none;" class="coordinates-label">Longitude: </span><span style="display:none;"  class="coordinates" id="longitude"><img class="pic-loading" src="loading.gif" alt="Get Browser Geolocation">Loading...</span>
		<div style="display:none;" id="map_image" style="width: 800px; height: 450px">
		<!-- Google Maps Canvas-->
		</div>
		<script type="text/javascript">
		 if (!navigator.geolocation)
		 {
		  document.getElementById('latitude').innerHTML = "Desconhecido";
		  document.getElementById('longitude').innerHTML = "Desconhecido";
		  document.getElementById('address').innerHTML = "Desconhecido";
		  alert("O seu browser não suporta os serviços.");
		 }
		</script>
Edited by PF2G
  • 3 weeks later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.