Google Maps API v3 ve MongoDB kullanımının basit bir uygulaması için bakabilirsiniz.
Başla
Spring MVC Google Maps API Kulanımı Örneği
Basit bir veri yapısı MongoDB' de nasıl tutulur. Bu verileri Java tarafında nasıl eşlenir. Veriler (maker) Google Maps API ile nasıl gösterilebilir. Bakalım.
Projenin Son Hali Aşağıdaki Gibi Olacak
Kullanılan Teknolojiler
- Spring 4.1.6.RELEASE
- Maven 4
- Google MAP APIv3 & markerCluster
- MongoDB
- Angular
- Bootstrap
- Netbeans 8.2
- Java EE 7 & Glashfish 4.1
Adım 1 :
Netbeans Maven Web Projesi Oluşturalım
Adım 2 :
Aşağıdaki Dosya Yapısını Gerçekleştirelim
Adım 3 :
pom.xml Dosyamızı Düzenleyelim
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mycompany</groupId> <artifactId>AngularGoogleMap</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>AngularGoogleMap</name> <properties> <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <jstl.version>1.2</jstl.version> <javax.servlet.version>3.0.1</javax.servlet.version> </properties> <dependencies> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> <!-- spring-context which provides core functionality --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.6.RELEASE</version> </dependency> <!-- The spring-aop module provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.1.6.RELEASE</version> </dependency> <!-- The spring-webmvc module (also known as the Web-Servlet module) contains Spring’s model-view-controller (MVC) and REST Web Services implementation for web applications --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.6.RELEASE</version> </dependency> <!-- The spring-web module provides basic web-oriented integration features such as multipart file upload functionality and the initialization of the IoC container using Servlet listeners and a web-oriented application context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.6.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${javax.servlet.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <!--Mongo Driver--> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.8.0.RELEASE</version> </dependency> <!--Twitter Bootstrap--> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>3.2.0</version> <exclusions> <exclusion> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>2.1.1</version> </dependency> <!--AngularJS--> <dependency> <groupId>org.webjars.bower</groupId> <artifactId>angularjs</artifactId> <version>1.4.7</version> </dependency> <!--MarkerCluster --> <dependency> <groupId>org.webjars</groupId> <artifactId>leaflet-markercluster</artifactId> <version>0.4.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> <compilerArguments> <endorseddirs>${endorsed.dir}</endorseddirs> </compilerArguments> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.6</version> <executions> <execution> <phase>validate</phase> <goals> <goal>copy</goal> </goals> <configuration> <outputDirectory>${endorsed.dir}</outputDirectory> <silent>true</silent> <artifactItems> <artifactItem> <groupId>javax</groupId> <artifactId>javaee-endorsed-api</artifactId> <version>7.0</version> <type>jar</type> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
Adım 4 :
WebInitializer.java
package com.mycompany.config; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; /** * * @author gurkan0791 */ public class WebInitializer implements WebApplicationInitializer{ @Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(Config.class); ctx.setServletContext(servletContext); ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx)); servlet.addMapping("/"); servlet.setLoadOnStartup(1); } }
Adım 5 :
Config.java
package com.mycompany.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; /** * * @author gurkan0791 */ @Configuration @ComponentScan("com.mycompany") @EnableWebMvc public class Config extends WebMvcConfigurerAdapter{ @Bean public ViewResolver viewResolver(){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/view/jsp/"); viewResolver.setSuffix(".jsp"); // viewResolver.setOrder(0); return viewResolver; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
Adım 6 :
MongoConfig.java
package com.mycompany.config; import com.mongodb.MongoClient; import com.mycompany.model.MarkerDAO; import com.mycompany.model.MarkerDAOImpl; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; /** * * @author gurkan0791 */ @Configuration public class MongoConfig { @Bean public MongoDbFactory mongoDbFactory() throws Exception { return new SimpleMongoDbFactory(new MongoClient("localhost", 27017), "local"); } @Bean public MongoTemplate mongoTemplate() throws Exception { MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory()); return mongoTemplate; } @Bean public MarkerDAO getContactDAO() { return new MarkerDAOImpl(); } public static MongoOperations getMongoConnection(){ ApplicationContext ctx = new AnnotationConfigApplicationContext(MongoConfig.class); MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate"); return mongoOperation; } }
Adım 7 :
Marker.java
package com.mycompany.model; import java.io.Serializable; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; /** * * @author gurkan0791 */ @Document(collection = "markers") public class Marker implements Serializable{ @Id private String _id; private String lat; private String lng; private String icon; private String content; private String title; /** * @return the icon */ public String getIcon() { return icon; } /** * @param icon the icon to set */ public void setIcon(String icon) { this.icon = icon; } /** * @return the content */ public String getContent() { return content; } /** * @param content the content to set */ public void setContent(String content) { this.content = content; } /** * @return the title */ public String getTitle() { return title; } /** * @param title the title to set */ public void setTitle(String title) { this.title = title; } /** * @return the lat */ public String getLat() { return lat; } /** * @param lat the lat to set */ public void setLat(String lat) { this.lat = lat; } /** * @return the lng */ public String getLng() { return lng; } /** * @param lng the lng to set */ public void setLng(String lng) { this.lng = lng; } /** * @return the _id */ public String getId() { return _id; } /** * @param _id the _id to set */ public void setId(String _id) { this._id = _id; } }
Adım 8 :
MarkerDAO.java
package com.mycompany.model; import java.util.List; /** * * @author gurkan0791 */ public interface MarkerDAO { public void saveOrUpdate(Marker marker); public void delete(String markerId); public List<Marker> markerListAll(); }
Adım 9 :
MarkerDAOImpl.java
package com.mycompany.model; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mycompany.config.MongoConfig; import java.util.List; import org.bson.types.ObjectId; /** * * @author gurkan0791 */ public class MarkerDAOImpl implements MarkerDAO{ @Override public void saveOrUpdate(Marker marker) { DBCollection markerCollection = MongoConfig.getMongoConnection().getCollection("markers"); BasicDBObject document = new BasicDBObject(); document.put("lat", marker.getLat()); document.put("lng", marker.getLng()); document.put("title", marker.getTitle()); document.put("icon", marker.getIcon()); document.put("content", marker.getContent()); if (marker.getId().length() > 0) { BasicDBObject query = new BasicDBObject(); query.append("_id", new ObjectId(marker.getId())); markerCollection.update(query, document); }else{ markerCollection.insert(document); } } @Override public void delete(String markerId) { DBCollection markerCollection = MongoConfig.getMongoConnection().getCollection("markers"); BasicDBObject query = new BasicDBObject(); query.append("_id", new ObjectId(markerId)); markerCollection.remove(query); } @Override public List<Marker> markerListAll() { List<Marker> listUser=MongoConfig.getMongoConnection().findAll(Marker.class, "markers"); return listUser; } }
Adım 10 :
DatabaseController.java
package com.mycompany.controllers; import com.mycompany.model.Marker; import com.mycompany.model.MarkerDAO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** * * @author gurkan0791 */ @Controller public class DatabaseController { @Autowired private MarkerDAO markerDAO; @RequestMapping(value = "/" , method = RequestMethod.GET) public String index(@ModelAttribute Marker marker,ModelMap map) { //MongoDBTest mongoDBTest = new MongoDBTest(); map.put("msg", "Hello Spring 4 Web MVC!"); map.put("mark", markerDAO.markerListAll()); //map.put("mark", mongoDBTest.getMarker()); return "index"; } @RequestMapping(value = "/insert" , method = RequestMethod.GET) public String insert(@ModelAttribute Marker marker){ markerDAO.saveOrUpdate(marker); // System.out.println("Marker Bilgi : "+marker.getTitle()+"\n"+marker.getContent()+"\n"+marker.getIcon() // +"\n"+marker.getId()+"\n"+marker.getLat()+"\n"+marker.getLng()); return "redirect:/"; } @RequestMapping(value = "/delete", method = RequestMethod.GET, params = {"id"}) public String delete(@RequestParam("id") String id){ //System.out.println("Delete id :"+ id); markerDAO.delete(id); return "redirect:/"; } }
Adım 11 :
app.js
(function(){ var app=angular.module('myApp', ['ngMap']); app.controller('MarkerCtrl',['$scope', function($scope) { var beforeMarker = null; //var markers = []; $scope.deleteID = ""; $scope.elements = elements; $scope.isDelete = true; var map; var infoWindow; $scope.dynMarkers = []; $scope.$on('mapInitialized', function(evt, evtMap) { map = evtMap; for (var i=0; i<$scope.elements.length; i++) { setMarker(map,new google.maps.LatLng($scope.elements[i].latLng[0],$scope.elements[i].latLng[1]),$scope.elements[i].title, $scope.elements[i].icon,$scope.elements[i].content,$scope.elements[i].id); } $scope.markerClusterer = new MarkerClusterer(map, $scope.dynMarkers, {}); $scope.placeMarker = function(e) { var marker; if (beforeMarker !== null) { beforeMarker.setMap(null); marker = new google.maps.Marker({position: e.latLng, map: map}); map.panTo(e.latLng); $("#lat").val(marker.position.lat); $("#lng").val(marker.position.lng); $("#id").val(""); $("#title").val(""); $("#icon").val(""); $("#content").val(""); $('#addOrUpdate').val('ADD MARKER'); $scope.isDelete = true; }else { marker = new google.maps.Marker({position: e.latLng, map: map}); map.panTo(e.latLng); $("#lat").val(marker.position.lat); $("#lng").val(marker.position.lng); $("#id").val(""); $("#title").val(""); $("#icon").val(""); $("#content").val(""); $('#addOrUpdate').val('ADD MARKER'); $scope.isDelete = true; } beforeMarker = marker; } }); function setMarker(map, position, title, icon, content,id) { var marker; var markerOptions = { position: position, map: map, title: title, icon: icon, content: content, id:id }; marker = new google.maps.Marker(markerOptions); //markers.push(marker); // add marker to array $scope.dynMarkers.push(marker); google.maps.event.addListener(marker, 'click', function () { // close window if not undefined if (infoWindow !== void 0) { infoWindow.close(); } // create new window var infoWindowOptions = { content: content }; infoWindow = new google.maps.InfoWindow(infoWindowOptions); infoWindow.open(map, marker); $("#id").val(marker.id); $("#lat").val(marker.position.lat); $("#lng").val(marker.position.lng); $("#title").val(marker.title); $("#icon").val(marker.icon); $("#content").val(marker.content); $('#addOrUpdate').val('UPDATE MARKER'); $scope.$apply(function () { $scope.isDelete = false; $scope.deleteID = marker.id; }); }); } }]); })();
Adım 12 :
index.jsp
<%-- Document : index Created on : Oct 20, 2015, 7:56:10 PM Author : gurkan0791 --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:set var="cp" value="${pageContext.request.servletContext.contextPath}" scope="request"></c:set> <!DOCTYPE html> <html ng-app="myApp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1"> <!--<link rel="stylesheet" type="text/css" href="${cp}/resources/css/site.css" />--> <link rel='stylesheet' href='${cp}/webjars/bootstrap/3.2.0/css/bootstrap.min.css'> <!--<link rel='stylesheet' href='${cp}/webjars/leaflet-markercluster/0.4.0/MarkerCluster.css'>--> <title>JSP Page</title> <script> var elements = [ <c:forEach var="row" items="${mark}"> {"id": '<c:out value="${row.id}" />', "latLng" : [<c:out value="${row.lat}" />, <c:out value="${row.lng}" />], "title" : '<c:out value="${row.title}" />', "icon": '<c:out value="${row.icon}" />', "content" : '<c:out value="${row.content}" />'}, </c:forEach> ]; </script> </head> <body> <div ng-controller="MarkerCtrl"> <div class="container"> <h1>GOOGLE MAP V3 ANGULARJS MONGODB DEMO</h1> </div> <map style="height: 500px;" center="39.095963, 35.419922" zoom="6" scrollwheel="false" center="36.900,30.70 " map-type-id="ROADMAP" on-click="placeMarker()"> </map> <br /> <hr /> <div class="container text-center"> <h2><p>MAKER INFORMATION</p></h2> <!--<p id="demo">Click me to change my HTML content (innerHTML).</p>--> <div ng-show="{{deleteID !== null }}"> <form:form class="form-horizontal" modelAttribute="marker" action="${cp}/insert" method="GET" > <form:hidden path="id" name="id" id="id" /> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">Lat</label> <div class="col-sm-10"> <form:input path="lat" type="text" class="form-control" id="lat" placeholder="Lat" disabled="disabled" /> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Lng</label> <div class="col-sm-10"> <form:input path="lng" type="text" class="form-control" id="lng" placeholder="Lng" disabled="disabled"/> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Title</label> <div class="col-sm-10"> <form:input path="title" type="text" class="form-control" id="title" placeholder="Marker Title here!" /> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Icon</label> <div class="col-sm-10"> <form:input path="icon" type="text" class="form-control" id="icon" placeholder="Marker Icon Here!" /> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Content</label> <div class="col-sm-10"> <form:input path="content" type="text" class="form-control" id="content" placeholder="Marker Content Here!" /> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type="submit" class="btn btn-success" value="ADD MARKER" id="addOrUpdate" /> <a href="${cp}/delete?id={{deleteID}}" class="btn btn-warning" ng-disabled="isDelete" id="deleteMarker" >DELETE Marker</a> </div> </div> </form:form> </div> </div> </div> <!--Script Bootstrap & Jquery --> <!--src="https://maps.googleapis.com/maps/api/js?sensor=false&v=3.exp&libraries=places&signed_in=true®ion=tr&language=tr&key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM"--> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=weather,visualization,panoramio"></script> <script type="text/javascript" src="${cp}/webjars/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script type="text/javascript" src="${cp}/webjars/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript" src="${cp}/webjars/angularjs/1.4.7/angular.min.js"></script> <script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script> <!--<script type="text/javascript" src="${cp}/webjars/leaflet-markercluster/0.4.0/leaflet.markercluster.js"></script>--> <!--<script type="text/javascript" src="${cp}/webjars/leaflet-markercluster/0.4.0/leaflet.markercluster-src.js"></script>--> <script type="text/javascript" src="${cp}/resources/js/markercluster.js"></script> <script type="text/javascript" src="${cp}/resources/js/app.js"></script> </body> </html>
Adım 14 :
MongoDB' de Tutulacak Veri Yapısı
/* 1 */ { "_id" : ObjectId("56288336404341fde27eca35"), "lat" : "36.9", "lng" : "30.700000000000045", "title" : "Title1", "icon" : "https://maps.google.com/mapfiles/ms/icons/orange-dot.png", "content" : "Content1new" } /* 2 */ { "_id" : ObjectId("56288367404341fde27eca36"), "lat" : 36.8999999999999986, "lng" : 30.7004200000000012, "title" : "Title2", "icon" : "https://maps.google.com/mapfiles/ms/icons/orange-dot.png", "content" : "Content2" }
Adım 15 :
MongoDB UI Desteği İçin RoboMongo İle Bağlanma
İlk önce MongoDB Kuralım. Ubuntu kurulum için
Robomongo' yu açalım ve "Create" ile yeni bir bağlantı oluşturalım ve "Connect" ile bağlantıyı gerçekleştirelim( :27017 Varsayılan port).
"local" isimli veritabanımızda "Collection" sağ tıklayalım ve "markers" adında yeni bir collection( tablo) oluşturalım.
please send me code surendra88meena@gmail.com
YanıtlaSilSource Code
Silplease send me code
YanıtlaSilhttps://github.com/gurkan0791/AngularGoogleMap
Sil