blog

Spring MVC + JQuery + Google MapでIP位置検索アプリケーションを作る

この記事では、Spring MVCフレームワークとjQueryとGoogle Mapを使用して、IPロケーションルックアップアプリケーションを作成する方法を説明します。ユーザーがIPアドレスをページに...

Jun 22, 2025 · 14 min. read
シェア

この記事では、読者は SpringMVCフレームワークとjQueryとGoogle Mapを使用して、検索アプリケーションに基づいて単純なIPロケーションを作成する方法を学びます。ユーザーはページにIPアドレスを入力することができ、その後、Googleマップを介して、おおよその地理的位置のIPロケーションを表示します。このチュートリアルの完了後、その効果は次のとおりです:

このチュートリアルでは、以下のテクニックを使用します:

  1. Spring MVC frameworks
  2. jQuery(Ajax Request)
  3. GeoLite
  4. Google Map

ここで、ユーザーは次のように進みます:

  1. ユーザーはIPアドレスを入力し、[送信]ボタンをクリックします。
  2. jQueryは SpringMVCのコントローラにAjaxリクエストを送信します。
  3. Spring "MVCコントローラでのJSONデータの処理とリターン
  4. jQueryは返されたjsonデータを処理し、Google Mapを介してユーザーに表示します。

1 プロジェクト体制

MAVENプロジェクトを使用したプロジェクト構造を以下に示します。

ここで、特別なジオデータベース GeoLite をダウンロードする必要があります。GeoLite フォーマットで IP データベースをダウンロードするアドレスは次の通りです: http://...///te/ をダウンロードし、ce フォルダに置きます。

2 MAVEN パッケージの依存関係

このプロジェクトの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> 
    //... 

#p#

3 Spring MVC+Geo Lite

インターフェイスの地理的な場所を見つけるためにIPによると、次の最初の書き込みは、ServerLocationBo.javaという名前のコードは次のとおりです:

package com.mkyong.web.location; 
 
ublic 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; 
  
    } 
} 

上記のメソッドでは、getLocationsメソッドでは、GeoLite形式のIPアドレスライブラリファイルGeoLiteCity.datをロードし、IP検索用のgetLocationメソッドを呼び出します。getLocationメソッドでは、GeoLiteは、クエリにIPアドレスライブラリファイルを渡すLookupServiceクラスのインスタンスを作成し、クエリにgetLocationメソッドを呼び出すには、クエリの結果は、serverLocationオブジェクトに構築され、次のコードを見てその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 
  
} 

そして、jsonへの変換結果に対してSpringMVCフレームワークJacksonを使用します:

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; 
  
    } 
  
} 

これは SpringMVCに慣れたユーザーには馴染みのないものではないはずです。変換結果は文字列に変換されます。

#p#

4 最終結果を表示するJSP+jQuery+Google Map

最後に、ページでは、jQueryを介して "春 "MVC制御層を呼び出すためにajaxリクエストを送信し、結果がページを表示するために返される、コードは次のとおりです:

<html> 
<head> 
<script src="http://..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> 

この記事のコードは次のアドレスからダウンロードできます:- //// --.ip

Read next

白輝CRMは華裕航空宇宙と契約し、健康商品のマーケティングを推進する

華友天は山東省に本社を置き、西安、煙台、東京に支社があり、その販売モデルはチャネルエージェントの発展に基づいており、東京支社は重要なマーケティング業務を担当しています。明るい市場展望を背景に、異なる組織間の情報と管理効率の欠如が、会社の急速な発展の制約となっています。

Jun 22, 2025 · 1 min read