Spring MVC –使用IP地址查找位置(jQuery + Google Map)

spring-mvc-ajax-google-map-1

在本教程中,我们将向您展示如何使用以下技术使用IP地址查找位置:

  1. Spring MVC框架。
  2. jQuery(Ajax请求)。
  3. GeoLite数据库。
  4. 谷歌地图。

查看教程流程

  1. 带有文本输入和按钮的页面。
  2. 输入IP地址,然后单击按钮。
  3. jQuery向Spring Controller发出Ajax请求。
  4. Spring控制器处理并返回json字符串。
  5. jQuery处理返回的json并在Google Map上显示位置。

1.项目目录

查看最终的项目目录结构,这是一个标准的Maven项目。

spring-mvc-ajax-google-map-directory

注意
下载免费的GeoLite免费数据库– GeoLiteCity.dat ,并将其放入resources文件夹。

2.项目依赖

声明Spring框架,Jackson和geoip-api依赖性。

pom.xml
//...
	<properties>
		<spring.version>3.2.2.RELEASE</spring.version>
		<maxmind.geoip.version>1.2.10</maxmind.geoip.version>
		<jackson.version>1.9.10</jackson.version>
	</properties>

	<dependencies>

		<!-- Spring Core -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- need this for @Configuration -->
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2.2</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- ip to server location -->
		<dependency>
			<groupId>com.maxmind.geoip</groupId>
			<artifactId>geoip-api</artifactId>
			<version>${maxmind.geoip.version}</version>
		</dependency>

		<!-- Jackson -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>${jackson.version}</version>
		</dependency>

	</dependencies>
	//...

3. Spring MVC + GeoLite

使用GeoLite数据库获取位置。

ServerLocationBo.java
package com.mkyong.web.location;

public interface ServerLocationBo {

	ServerLocation getLocation(String ipAddress);

}
ServerLocationBoImpl.java
package com.mkyong.web.location;

import java.io.IOException;
import java.net.URL;
import org.springframework.stereotype.Component;
import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;
import com.maxmind.geoip.regionName;

@Component
public class ServerLocationBoImpl implements ServerLocationBo {

	@Override
	public ServerLocation getLocation(String ipAddress) {

		String dataFile = "location/GeoLiteCity.dat";
		return getLocation(ipAddress, dataFile);

	}

	private ServerLocation getLocation(String ipAddress, String locationDataFile) {

	  ServerLocation serverLocation = null;

	  URL url = getClass().getClassLoader().getResource(locationDataFile);

	  if (url == null) {
		System.err.println("location database is not found - "
			+ locationDataFile);
	  } else {

	  try {

		serverLocation = new ServerLocation();

		LookupService lookup = new LookupService(url.getPath(),
				LookupService.GEOIP_MEMORY_CACHE);
		Location locationServices = lookup.getLocation(ipAddress);

		serverLocation.setCountryCode(locationServices.countryCode);
		serverLocation.setCountryName(locationServices.countryName);
		serverLocation.setRegion(locationServices.region);
		serverLocation.setRegionName(regionName.regionNameByCode(
			locationServices.countryCode, locationServices.region));
		serverLocation.setCity(locationServices.city);
		serverLocation.setPostalCode(locationServices.postalCode);
		serverLocation.setLatitude(
                                String.valueOf(locationServices.latitude));
		serverLocation.setLongitude(
                                String.valueOf(locationServices.longitude));

	  } catch (IOException e) {

		System.err.println(e.getMessage());

	  }

	 }

	 return serverLocation;

	}
}
ServerLocation.java
package com.mkyong.web.location;

public class ServerLocation {

	private String countryCode;
	private String countryName;
	private String region;
	private String regionName;
	private String city;
	private String postalCode;
	private String latitude;
	private String longitude;

	//getter and setter methods

}

Spring控制器,使用Jackson库转换ServerLocation ,然后返回json字符串。

MapController.java
package com.mkyong.web.controller;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.mkyong.web.location.ServerLocation;
import com.mkyong.web.location.ServerLocationBo;

@Controller
public class MapController {

	@Autowired
	ServerLocationBo serverLocationBo;

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView getPages() {

		ModelAndView model = new ModelAndView("map");
		return model;

	}

	//return back json string
	@RequestMapping(value = "/getLocationByIpAddress", method = RequestMethod.GET)
	public @ResponseBody
	String getDomainInJsonFormat(@RequestParam String ipAddress) {

		ObjectMapper mapper = new ObjectMapper();

		ServerLocation location = serverLocationBo.getLocation(ipAddress);

		String result = "";

		try {
			result = mapper.writeValueAsString(location);
		} catch (Exception e) {

			e.printStackTrace();
		}

		return result;

	}

}

4. JSP + jQuery + Google Map

单击搜索按钮后,jQuery会发出Ajax请求,处理数据并更新Google Map。

map.jsp
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
  <h2>Spring MVC + jQuery + Google Map</h2>

  <div>
	<input type="text" placeholder="0.0.0.0" id="w-input-search" value="">
	<span>
		<button id="w-button-search" type="button">Search</button>
	</span>
  </div>

  <script>
  $(document).ready(function() {

	$("#w-button-search").click(function() {
	
		$.getJSON("${pageContext.request.contextPath}/getLocationByIpAddress",
		{
			ipAddress : $('#w-input-search').val()
		}, 
		function(data) {
				
			var data = JSON.stringify(data);
			var json = JSON.parse(data);
				
			showMap(json["latitude"],json["longitude"])
				
			$("#result").html(data)
				
		})
		.done(function() {							
		})
		.fail(function() { 
		})
		.complete(function() { 			
		});
			
	});
		
	var map;
		
	function showMap(latitude,longitude) { 
			
		var googleLatandLong = new google.maps.LatLng(latitude,longitude);
		
		var mapOptions = { 
			zoom: 5,
			center: googleLatandLong,
			mapTypeId: google.maps.MapTypeId.ROADMAP 
		};
		
		var mapDiv = document.getElementById("map");
		map = new google.maps.Map(mapDiv, mapOptions);
			
		var title = "Server Location"; 
		addMarker(map, googleLatandLong, title, "");
			
	}
		
	function addMarker(map, latlong, title, content) { 
			
		var markerOptions = {
			position: latlong, 
			map: map,
			title: title, 
			clickable: true
		};
		var marker = new google.maps.Marker(markerOptions); 
	}
		
  });
  </script>
  <br/>
  <div id="result"></div>
  <br/>
  <div style="width:600px;height:400px" id="map"></div>

</body>
</html>

5.演示

IP地址:74.125.135.102

spring-mvc-ajax-google-map-1

IP地址:183.81.166.110

spring-mvc-ajax-google-map-2

下载源代码

下载它– SpringMvc-jQuery-GoogleMap (18 KB)

参考文献

  1. 维基百科:地理定位软件
  2. GeoLite免费可下载数据库
  3. Java –使用IP地址查找位置
  4. Google Map API
  5. jQuery.getJSON

翻译自: https://mkyong.com/spring-mvc/spring-mvc-find-location-using-ip-address-jquery-google-map/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值