В этом руководстве мы покажем вам, как найти местоположение с помощью IP-адреса с помощью следующих технологий:
- Фреймворки Spring MVC.
- jQuery (запрос Ajax).
- База данных геолокации.
- Карта Google.
Просмотрите потоки учебника
- Страница с вводом текста и кнопкой.
- Введите IP-адрес и нажмите на кнопку.
- jQuery отправляет Ajax-запрос контроллеру Spring.
- Контроллер Spring обрабатывает и возвращает строку json.
- jQuery обрабатывает возвращенный json и отображает местоположение на карте Google.
1. Каталог проектов
Просмотрите окончательную структуру каталогов проекта, стандартный проект Maven.
2. Зависимости проекта
Объявляет зависимости Spring framework, Jackson и geoip-api.
//...3.2.2.RELEASE 1.2.10 1.9.10 //... org.springframework spring-core ${spring.version} cglib cglib 2.2.2 org.springframework spring-web ${spring.version} org.springframework spring-webmvc ${spring.version} com.maxmind.geoip geoip-api ${maxmind.geoip.version} org.codehaus.jackson jackson-mapper-asl ${jackson.version}
3. Весенний MVC + геолит
Получите местоположение с помощью базы данных GeoLite.
package com.mkyong.web.location; public interface ServerLocationBo { ServerLocation getLocation(String ipAddress); }
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; } }
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, преобразует Местоположение сервера
с библиотекой Джексона
и возвращает строку json.
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
При нажатии кнопки поиска jQuery запускает запрос Ajax, обрабатывает данные и обновляет карту Google.
Spring MVC + jQuery + Google Map
5. Демонстрация
IP-адрес: 74.125.135.102
IP-адрес: 183.81.166.110
Скачать Исходный Код
Рекомендации
- Википедия: Программное обеспечение для геолокации
- Бесплатные загружаемые базы данных GeoLite
- Java – Поиск местоположения по IP-адресу
- API-интерфейсы карт Google
- API-интерфейсы карт Google
Оригинал: “https://mkyong.com/spring-mvc/spring-mvc-find-location-using-ip-address-jquery-google-map/”