Friday, January 18, 2013

J2ME Google Maps API (Portugu?s)

?

Line 22: Line 22:
?

|author= [[User:Jappit]]

?

|author= [[User:Jappit]]

?

}}

?

}}

?+
?+

{{Archived|timestamp=20130201151019|user=[[User:Jasfox|Jasfox]]|

?+

Since this article was written, alternative '''Map Tile caching''' solutions for Java ME have become available. '''Map Tile caching''' solutions such as the [http://developer.here.net/java Nokia Maps API for Java ME] have several advantages over '''static mapping''' solutions such as the static Google Maps API? including:

?+

* '''Static''' mapping services such as the Google Static Maps API or Nokia's [http://api.maps.nokia.com/en/restmaps/overview.html RESTful Map API] do not cache or tile the images when requested, therefore '''each''' request involves a round trip to the server. If the map on a mobile application needs to be refreshed at any time, using a caching library will result in a reduction in network traffic after around '''three''' maps have been displayed. An explanation of this can be found? [http://www.developer.nokia.com/Community/Wiki/Using_the_RESTful_Map_API_with_Java_ME#Comparision_of_Network_traffic_generated_by_the_RESTful_Map_API_and_Maps_API_for_Java_ME here]

?+

* As the name implies, Google's Static Maps API can only retrieve over http static images for a requested coordinate point, image size, image type and zoom level. Newer libraries offer additional functionality out of the box offering dynamic Map content and touch support, where the user can move around his/her current position, zoom in, zoom out, modify the view mode to satellite or translate an address to a coordinate point and show that on the map, among others. This abstraction of the underlying functionality is hidden from the developer,os much less coding is needed in order to achieve the same result .

?+

Additionally the following points apply in favour of Nokia Maps when comparing to Google Maps:

?+

* No legal restrictions of using the API outside a web browser application or need to provide a link to the native Google Maps App (if there is one), or to Google Maps (if there isn't one). See Terms of Service below.

?+

* Higher free daily request limits. Nokia Maps API for Java ME supports up to 50,000 render requests per day and per unique IP address (as of January 2012), for Nokia Developer registered users (free of charge) while the limit for Google's Static Maps API is currently 1000 unique (different) image requests per viewer per day.

?+

An article with the same functionality, written with Nokia Maps API for Java ME, that uses much less code can be found [[How to display an Address or a Point of Interest on a Map with Java ME|here]] }}

?+
?+
?

Aqui est? uma biblioteca simples para consultar o Google Maps com as seguintes caracter?sticas:

?

Aqui est? uma biblioteca simples para consultar o Google Maps com as seguintes caracter?sticas:

?

* Endere?os de geoc?digos para suas coordenadas geogr?ficas ?

?

* Endere?os de geoc?digos para suas coordenadas geogr?ficas ?


Latest revision as of 17:06, 18 January 2013

Dados do artigo

Exemplo de c?digo
Testado com

Aparelho(s): Nokia X3-02, Nokia 6210N, Nokia 6233, Nokia 701


Compatibilidade

Plataforma(s): Series 40, Symbian

Device(s): since Series 40 6th Edition, since Symbian S60 3rd Edition


Artigo

Tradu??o:

?ltima altera??o feita por jasfox em 18 Jan 2013 Archived:?This article is archived because it is not considered relevant for third-party developers creating commercial solutions today. If you think this article is still relevant, let us know by adding the template {{ReviewForRemovalFromArchive|user=~~~~|write your reason here}}.

Since this article was written, alternative Map Tile caching solutions for Java ME have become available. Map Tile caching solutions such as the Nokia Maps API for Java ME have several advantages over static mapping solutions such as the static Google Maps API including:

  • Static mapping services such as the Google Static Maps API or Nokia's RESTful Map API do not cache or tile the images when requested, therefore each request involves a round trip to the server. If the map on a mobile application needs to be refreshed at any time, using a caching library will result in a reduction in network traffic after around three maps have been displayed. An explanation of this can be found here
  • As the name implies, Google's Static Maps API can only retrieve over http static images for a requested coordinate point, image size, image type and zoom level. Newer libraries offer additional functionality out of the box offering dynamic Map content and touch support, where the user can move around his/her current position, zoom in, zoom out, modify the view mode to satellite or translate an address to a coordinate point and show that on the map, among others. This abstraction of the underlying functionality is hidden from the developer,os much less coding is needed in order to achieve the same result .

Additionally the following points apply in favour of Nokia Maps when comparing to Google Maps:

  • No legal restrictions of using the API outside a web browser application or need to provide a link to the native Google Maps App (if there is one), or to Google Maps (if there isn't one). See Terms of Service below.
  • Higher free daily request limits. Nokia Maps API for Java ME supports up to 50,000 render requests per day and per unique IP address (as of January 2012), for Nokia Developer registered users (free of charge) while the limit for Google's Static Maps API is currently 1000 unique (different) image requests per viewer per day.
An article with the same functionality, written with Nokia Maps API for Java ME, that uses much less code can be found here


Aqui est? uma biblioteca simples para consultar o Google Maps com as seguintes caracter?sticas:

  • Endere?os de geoc?digos para suas coordenadas geogr?ficas
  • Recupera??o de imagens est?ticas com tamanho, formato e ?zoom? configur?veis.

Para ver um exemplo real desta API, voc? pode acessar aqui: Java ME Google Maps API sample MIDlet

Pegue sua pr?pria Google Maps API Key

Para usar o seguinte c?digo, voc? dever? pegar sua pr?pria Google Maps API Key. Se voc? n?o tem uma API Key, voc? pode seguir as instru??es aqui: Como usar os dados do Google Maps em aplica??es m?veis

Use um servidor Proxy para acessar os servi?os do Google Maps

Nota: o tema (uso de proxy) provavelmente n?o ? necess?rio, mesmo assim o abordaremos.
Quando voc? obtiver uma Google Maps API key, voc? insere o endere?o e essa chave possibilitar? acessar os servi?os Google Maps. Por esta raz?o, voc? dever? configurar o servidor Proxy neste endere?o e este receber? requisi??es HTTP de seus clientes m?veis, remetendo-o para os servi?os do Google Maps, que responde de volta.

No c?digo abaixo, voc? dever? colocar a seguinte requisi??o:

  • http://www.yourserver.com/error.html requests to http://maps.google.com/maps/geo
  • http://www.yourserver.com/error.html requests to http://maps.google.com/staticmap

C?digo fonte: classe GoogleMaps

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
?
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Image;
?
public class GoogleMaps
{
String apiKey = null;
?
//estas duas propriedades ser?o usadas com o m?todo de rolagem dos mapas.Voc? pode remove-lo se n?o for necess?rio.
int offset = 268435456;
double radius = offset / Math.PI;
?
public GoogleMaps(String apiKey)
{
this.apiKey = apiKey;
}
?
public double[] geocodeAddress(String address) throws Exception
{
byte[] res = loadHttpFile(getGeocodeUrl(address));
?
String resString = new String(res, 0, res.length);
?
String[] data = split(resString, ',');
?
if(data[0].compareTo("200") != 0)
{
int errorCode = Integer.parseInt(data[0]);
?
throw new Exception("Google Maps Exception: " + getGeocodeError(errorCode));
}
else
{
return new double[]{
Double.parseDouble(data[2]),
Double.parseDouble(data[3])
};
}
}
public Image retrieveStaticImage(int width, int height, double lat, double lng, int zoom, String format) throws Exception
{
byte[] imageData = loadHttpFile(getMapUrl(width, height, lng, lat, zoom, format));
?
return Image.createImage(imageData, 0, imageData.length);
}
?
String getGeocodeError(int errorCode)
{
switch(errorCode)
{
case 400:
return "Bad request";
case 500:
return "Server error";
case 601:
return "Missing query";
case 602:
return "Unknown address";
case 603:
return "Unavailable address";
case 604:
return "Unknown directions";
case 610:
return "Bad API key";
case 620:
return "Too many queries";
default:
return "Generic error";
}
}
?
String getGeocodeUrl(String address)
{
return "http://maps.google.com/maps/geo?q=" + urlEncode(address)
+ "&output=csv&key=" + apiKey;
}
String getMapUrl(int width, int height, double lng, double lat, int zoom, String format)
{
return "http://maps.google.com/maps/api/staticmap?center=" +
lat + "," + lng + "&format=" + format + "&zoom=" + zoom + "&size=" +
width + "x" + height + "&key=" + apiKey;
}
String urlEncode(String str)
{
StringBuffer buf = new StringBuffer();
char c;
for(int i = 0; i < str.length(); i++)
{
c = str.charAt(i);
if ((c >= '0' && c <= '9')||
(c >= 'A' && c <= 'Z')||
(c >= 'a' && c <= 'z'))
{
buf.append(c);
}
else
{
buf.append("%").append(Integer.toHexString((int) str.charAt(i)));
}
}
return buf.toString();
}
byte[] loadHttpFile(String url) throws Exception
{
HttpConnection hc = null;
?
InputStream is = null;
?
byte[] byteBuffer = null;
?
try
{
hc = (HttpConnection) Connector.open(url);
?
hc.setRequestMethod(HttpConnection.GET);
?
int ch;
?
is = hc.openInputStream();
?
int len = (int)hc.getLength();
?
if(len > 0)
{
byteBuffer = new byte[len];
?
is.read(byteBuffer);
}
else
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
?
while ((ch = is.read()) != -1)
{
bos.write(ch);
}
byteBuffer = bos.toByteArray();
?
bos.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(is != null)
is.close();
?
if(hc != null)
hc.close();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
return byteBuffer;
}
static String[] split(String s, int chr)
{
Vector res = new Vector();
?
int curr = 0;
int prev = 0;
?
while((curr = s.indexOf(chr, prev)) >= 0)
{
res.addElement(s.substring(prev, curr));
?
prev = curr + 1;
}
res.addElement(s.substring(prev));
?
String[] splitted = new String[res.size()];
?
res.copyInto(splitted);
?
return splitted;
}
}

Utilidade do m?todo de rolagem para o mapa

Se voc? necessita de usar rolagem no seu mapa, voc? precisa calcular o novo centro para sua imagem est?tica. O m?todo adjust() retornar? o novo centro de latitude e longitude do mapa, aceitando os seguintes argumentos:

  • as atuais coordenadas de latitute e longitude
  • o deltaX e deltaY, em pixels, do centro do mapa
  • o n?vel de zoom


O c?digo original, em JavaScript, est? disp?nivel em: http://home.provide.net/~bratliff/adjust.js

Nota: para usar o seguinte m?todo, voc? dever? incluir no seu projeto a biblioteca MicroFloat, dispon?vel em: MicroFloat website

public double[] adjust(double lat, double lng, int deltaX, int deltaY, int z)
{
return new double[]{
XToL(LToX(lat) + (deltaX<<(21-z))),
YToL(LToY(lng) + (deltaY<<(21-z)))
};
}
double LToX(double x)
{
return round(offset + radius * x * Math.PI / 180);
}
?
double LToY(double y)
{
return round(
offset - radius *
Double.longBitsToDouble(MicroDouble.log(
Double.doubleToLongBits(
(1 + Math.sin(y * Math.PI / 180))
/
(1 - Math.sin(y * Math.PI / 180))
)
)) / 2);
}
?
double XToL(double x)
{
return ((round(x) - offset) / radius) * 180 / Math.PI;
}
?
double YToL(double y)
{
return (Math.PI / 2 - 2 * Double.longBitsToDouble(
MicroDouble.atan(
MicroDouble.exp(Double.doubleToLongBits((round(y)-offset)/radius))
)
)) * 180 / Math.PI;
}
double round(double num)
{
double floor = Math.floor(num);
?
if(num - floor >= 0.5)
return Math.ceil(num);
else
return floor;
}

C?digo fonte: uso simples

J2me google maps.jpg
Para usar esta classe, voc? primeiramente argumenta-a com sua API key:

GoogleMaps gMap = new GoogleMaps("API_KEY");

Para um endere?o em geoc?digo, voc? pode usar o m?todo geocodeAddress():

double[] lanLng = gMap.geocodeAddress("Leicester Square, London");

Para buscar imagem de um mapa:

Image map = gMap.retrieveStaticImage(320, 240, 51.510605, -0.130728, 8, "png32");

Source: http://www.developer.nokia.com/Community/Wiki/index.php?title=J2ME_Google_Maps_API_(Portugu%C3%AAs)&diff=182482&oldid=168079

kim mulkey sarah palin today show dallas tornado video 1940 census instagram for android dallas news dallas fort worth

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.