Google Maps API Initial Experience

Source: Internet
Author: User
Tags geoip maxmind

Recently really do not know what to do well, want to learn everything, but learn nothing, but experience a Google Maps API feel good, Google is really too strong, maybe it is my future goals.

For GMAPAPI Development, you first have to apply for Google Maps API Key, Http://code.google.com/intl/zh-CN/apis/maps/has a detailed introductory instructions, you can start a development trip after the key is obtained, I started with the developer's Guide provided by Google and then made an IP location visualization query system, albeit simple but very interesting, based on the examples in the book.

First need to download the IP database and related APIs, I chose the Maxmind free geolitecity database and have rich API support, geolitecity database download address for http://www.maxmind.com/download/ geoip/database/, choose to download GeoLiteCity.dat.gz and unzip, while downloading the official apihttp://www.maxmind.com/download/geoip/api/, you can choose your own good development language , I chose the Java API, the development environment is MyEclipse6.6.

Map location query is mainly divided into two steps, first, to obtain the IP to be queried; second, use the Maxmind API to query and return the query results. Create a new Web Project in MyEclipse, import the downloaded GeoIPJava-1.2.3 API, and place the IP database file GeoLiteCity.dat under Webroot.

The server side uses JSP, the following is the Java code for the <body> element in search.jsp:

<body>
<%
Get data from a user requesting a query
String querystring = (string) request.getparameter ("Q");
PrintWriter Outwriter;
String IP = "";
Returns the host address if the query data is empty
if (querystring = null | | querystring.equals ("")) {
ip = Inetaddress.getlocalhost (). toString ();
if (IP = null | | ip.equals (""))
SYSTEM.OUT.PRINTLN ("Cannot get your IP address!");
}
else {
Verify that the query data is a valid IP with a regular expression
String pattern = "^" (d{1,3}//.//d{1,3}//.//d{1,3}//.//d{1,3}) $ ";
if (querystring.matches (pattern)) {
ip = querystring;
System.out.println ("The IP address is valid.");
}
Verify that the query data is a valid domain name if it is not valid
else {
try {
ip = Inetaddress.getbyname (querystring). ToString ();
ip = ip.split ("/") [1];
if (!ip.matches (pattern)) {
System.out.println ("Invalid domain!");
Response.setcontenttype ("Text/xml");
Response.setcharacterencoding ("Utf-8");
Outwriter = Response.getwriter ();
Outwriter.print ("alert (' Invalid domain! ')");
}
}
catch (Unknownhostexception e) {
System.out.println ("Invalid domain!");
}
}
}
try {
Establish Lookupservice instance start query
Lookupservice query = new Lookupservice ("./geolitecity.dat", Lookupservice.geoip_standard);
Location Location = query.getlocation (IP);
Returns the query results, including the IP address location of the country name and code, region, city, and latitude
if (location!= null) {
String responsetext = "loadgeoinfo (' + querystring +" ', ' "+ IP +" ', ' ")
+ Location.countrycode + "', '" + Location.countryname + "', '"
+ location.region + "', '" + location.city + "',"
+ Location.latitude + "," + Location.longitude + ");";

Response.setcontenttype ("Text/xml");
Response.setcharacterencoding ("Utf-8");
Outwriter = Response.getwriter ();
System.out.println (ResponseText);
Outwriter.print (ResponseText);
}
else {
SYSTEM.OUT.PRINTLN ("The Information for" + IP + "isn't not available now.");
}
}
catch (FileNotFoundException e) {
SYSTEM.OUT.PRINTLN ("Cannot find the file!");
}
%>
</body>

The use of the GeoIPJava-1.2.3 API is also very simple, the core class of this library is the Lookupservice class, you can choose the appropriate method as needed. Note that Java itself provides java.net.inetaddress,java.net.* is the core class library of network programming, InetAddress provides the relevant processing of Internet Protocol (IP) address.

The client program uses AJAX technology. The Google Maps API itself provides a fairly easy way to use Ajax, with two main asynchronous invocation methods, one using the Gxmlhttp object and the other using the Gdownloadurl () function. I experimented with both methods, and the following query page index.html code:

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<title>geoip seeker</title>

<meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" >
<meta http-equiv= "description" content= "This are my page" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">

<!--<link rel= "stylesheet" type= "Text/css" href= "./styles.css" >-->

<!--import the Google Maps API, and note that the API key is replaced with its own-->
<script src= "http://maps.google.com/maps?file=api&amp;v=2&amp;key= Abqiaaaavzho6pilsogujfefrexl3hr957vyfaxvolu_ef_7zut9iexmpht-mjdyizc-avowgkyl8tek8rswog&sensor=false "Type=" Text/javascript ">
</script>
<script type= "Text/javascript" >
var map; Global GMap2 Object
var marker; Gmarker landmark for identifying query IP

Class
function Load () {
if (gbrowseriscompatible ()) {
Map = new GMap2 (document.getElementById ("map"));
Map.setcenter (New Glatlng (39.92, 116.46), 2);
Add appropriate control controls
Map.addcontrol (New Gsmallmapcontrol ());
Map.addcontrol (New Gmaptypecontrol ());
Set map type to mixed map
Map.setmaptype (G_HYBRID_MAP);
}
}

Enter the corresponding query bar
function Pressenter (event, q) {
Executes a query if a carriage return is entered
if (Event.keycode = | | event.keycode = 10) {
Createrequest (q);
}
}

Query functions, using the Gxmlhttp object
function Createrequest (q) {
var request = Gxmlhttp.create ();
var url = "Search.jsp";
Open the Gxmlhttp object to set three parameters, the first is the type post or get for the method, the second is the URL address to send the request, the third is get mode, synchronization is true asynchronous is false
Request.open ("POST", url, True);
Request.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
form data
var formData = "q=" + q;
A callback function that defines a response, either as a closed-pack form or as a separate call to the callback function
Request.onreadystatechange = function () {
if (request.readystate = = 4) {
if (Request.status = = 200) {
Getting data returned by the server side
Text = Request.responsetext;
Fun = Text.split ("n") [0];
alert (fun);
(fun);
}
else{
Alert ("Failed for searching!");
}
}
};
Send an asynchronous request
Request.send (FormData);
}

Query function, using Gdownloadurl () method
function Getgeoinfo (q) {
Gdownloadurl ("search.jsp?q=" + Q, Function (data) {
Fun = Data.split ("n") [0];
(fun);
})
}

Locate the destination IP on the map and add an information window to display the details
function Loadgeoinfo (q, IP, Country_code, country, region, city, Latitude, longtitude) {
Information content, including query data, IP, country name, country code, provinces, cities, and latitude
var info = "<div align=/" left/"style=/" OVERFLOW:X; font-size:12px/">"
+ "<span style=/" font-size:14px/"><strong>" + q + "</strong></span><br/>"
+ "<strong>IP:</strong> &nbsp;" + IP + "<br/>"
+ "<strong> National:</strong> &nbsp;" + Country + "<br/>"
+ "<strong> code:</strong> &nbsp;" + country_code + "<br/>"
+ "<strong> province:</strong> &nbsp;" + region + "<br/>"
+ "<strong> Urban:</strong> &nbsp;" + City + "<br/>"
+ "<strong> Longitude:</strong> &nbsp;" + longtitude + "<br/>"
+ "<strong> latitude:</strong> &nbsp;" + latitude + "<br/>"
+ "</div>";
var point = new Glatlng (latitude, longtitude);
Move the map to a new location
Map.panto (point);
If you create a marker landmark, close the current information window and remove the landmark
if (marker) {
Map.closeinfowindow ();
Map.removeoverlay (marker);
}
Create a new landmark
Marker = new Gmarker (point);
Map.addoverlay (marker);
Display Information window
Marker.openinfowindowhtml (info);
}
</script>
<style>
td{
Text-align:center;
}
</style>

<body onload= "Load ()" onunload= "Gunload ()" >
<table cellspacing= "0" cellpadding= "0" width= "0" border= "center" >
<tbody>
<tr>
&LT;TD height= ">"
<form onsubmit= "return false;" >
<label for= "Q" > Please enter IP or domain name
<input maxlength= "size=" name= "q" id= "Q" onkeypress= "Pressenter" (event, This.value); "/>
<input type= "button" value= "Find" id= "search" onclick= "Getgeoinfo (q.value);"/>
</label>
</form>
</td>
</tr>
<tr>
<td>
<div id= "Map" style= "width:750px;height:520px" ></div>
</td>
</tr>
</tbody>
</table>
</body>
The JavaScript section contains detailed comments on the use of the Google Maps API, as well as references to Google's official introductory guide or API instructions, and here are a few questions that I have encountered during the writing process.

One is the problem of Ajax. Here I use the above mentioned two methods, query if click on the query button will be executed Getgeoinfo method using the Gdownloadurl () function, if you press ENTER will perform Createrequest method using Gxmlhttp object, the effect is the same. Gxmlhttp objects and traditional XMLHttpRequest objects are basically no difference, data and methods are basically the same, including commonly used responsetext, onreadystatechange and other data, open (), send () and other methods. The Gdownloadurl (url,onload) function should be said to be a simplified version of the asynchronous processing function, can only use the Get method, do not judge the load state, but only after full load call the callback function, where the first parameter is the need to get the URL, The second parameter is a fully loaded callback function. The data data is equivalent to the responsetext of the Gxmlhttp object, that is, the query result returned by the server.

The second is a question about the callback function. The callback functions here are written in the form of closures and, of course, the callback functions can be presented separately. It is said that the latest feature of the upcoming j2se7.0 is to start supporting closures, indicating that Java has also begun to introduce closure features to excellent dynamic or scripting languages such as groovy, PHP, JS, and Python. The callback function suggests using the () function, direct execution function, simpler, no longer need to parse the returned data, but to note that the function of the parameter type, string class parameters must be enclosed in single quotes, I just made a long time () did not perform the last discovery is the problem.

Here is a demo of the program, and there are a few more interesting results:

The above two are Google and Google China's server address, one in Silicon Valley, one in Beijing, this is not surprising, but I magnified Google China's domain name location, the result is very embarrassing:

I also tested the Sina's server address, the landmark is also very embarrassing to fall in the North Sea Central, maxmind IP database latitude and longitude can only be accurate to the city.

Did not carefully check the peak elder brother to do the forum server address, the result is in my birthplace of Hefei, peak brother said he just rented a server outside in the end where also don't know, it seems that this can only be an unsolved mystery.

Finally, it is recommended to use Google's Chrome browser, Google Maps support is not generally good, the original use of IE when the map is always showing instability. Believe in Google, you have eternal life.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.