How to use HTML5 and MongoDB to create a location-aware Web program

Source: Internet
Author: User
Keywords We the application Java can

In our daily life, we are inseparable from the application of position recognition class. Apps like Foursquare and Facebook help us share our current location (or the sights we're visiting) with our family and friends. Apps like Google Local help us find out what services or businesses we need around our current location. So, if we need to find a café that's closest to us, we can get a quick suggestion via Google Local and start right away. This not only greatly facilitates the daily life, but also can help enterprises to sell their products to the more ideal audience groups. Whether it is to consumers or to enterprises, this is a perfect winning situation.

To create such an application, you first need to obtain the user's geographic information. According to Wikipedia, "geo-information refers to the physical location of an object." For the moment, there is no standardized user geographic access in Web applications. Although open source libraries such as Google gears have access to location information from users, the library has ceased to evolve, runs only in older browsers, and does not support the Geo-geographic API. The Geolocation API provides a set of specifications for accessing geographic information related to managed devices through standardized scripting. Geo location does not provide official support for HTML 5, but it still doesn't stop people from being enthusiastic, and we often hear developers docking the Geolocation API with HTML 5. The API builds an abstraction layer based on the geographic information that the user collects, ensuring that all browsers support the geo-positioning API. You can access the http://caniuse.com/#feat =geolocation get the following chart.

Application use cases-looking for a job application

In this article, we will create a geographically aware job application. The application will look for the nearest job search location based on the user's specific skills, such as Java, Scala, and MongoDB. Applications will use the Geolocation API to achieve user positioning. Next, the application paints the user's location in Google Maps. You can visit http://localjobshtml5-cix.rhcloud.com/to get this app. The user's icon corresponds to the user's current location, and the Briefcase icon corresponds to the target job location.

If you click on any Briefcase icon, the map will automatically enlarge as shown in the following image. And when we close the Information window, the screen shrinks again. In addition, you can see the distance between the job site and the current position in the tag, the corresponding position and other relevant information. The distance between the user location and the work location is supported by the MONGDB geospatial features, which we will discuss further in later articles.

Application Technology Stack

The use of the following technology stacks is required for the creation of this application:

Java EE 6: We will use several Java EE 6 spec--jax-rs as well as CDI. Jax is a Java API for RESTful Web services that provides Java APIs for network service creation based on rest schema mode. CDI is the acronym for context and Dependency injection (background and associated injection). CDI allows developers to bind and inject Java EE components with lifecycle backgrounds, and then interact in a loosely coupled manner through event triggering and observation mechanisms.

Mongodb:mongodb is a document-oriented NoSQL data storage mechanism. We will keep working data in MongoDB and use its geospatial capabilities in the application.

HTML 5: We will use HTML 5 to create the application client and use the Geolocation API to get the user's current location.

Google Maps: Apps will use Google Maps to address user locations and job search information.

OpenShift: The application will be deployed into the OpenShift public PAAs.

Application source Code

The source code for this application is published in GitHub, address: HTTPS://GITHUB.COM/SHEKHARGULATI/LOCALJOBSHTML5

Pre-renewal conditions

Before we begin to create an application, we need to set up the following tasks:

1. Register a OpenShift account. Account registration is free of charge, and Red Hat will provide free three sets of gear for each user to run the application. At the end of this article, this account will have 1.5GB memory capacity and 3GB disk storage space.

2. Install RHC client Tools on the device. RHC is a ruby gem package, so you need to install Ruby 1.8.7 or later on your device. To install RHC, you need to enter:

sudo gem install RHC

If Ruby is currently installed, make sure it is in the latest version. To update the RHC tool, follow the command shown below:

sudo gem update rhc

For additional relevant RHC command-line tool setup instructions, please click the following Web site to view the relevant information: Https://openshift.redhat.com/community/developers/rhc-client-tools-install

1 Use the RHC Setup command to set up the OpenShift account. This command will help you create a namespace and upload your SSH key to the OpenShift server.

Start creating applications

Now that we have completed all the previous setup work, we are now starting to create the application. We will start by creating the OpenShift application. When working with PAAs, it's important to be clear: PAAs is used to create applications. So now we're going to get rid of the idea of a virtual machine or a server-centric approach, and focus on the application.

Creating Jbosseap MongoDB OpenShift Applications

To create an application named "Localjobs" with Jbosseap and Mongdb, we first execute the following command:

RHC app Create Localjobs jbosseap mongodb-2.2

This will create a set of application containers for us, called Gear, and configure them with all the necessary selinux policies and cgroup configurations. OpenShift will also set up a private git library for us and clone the library to the local system. Finally, OpenShift sends DNS to the external environment. You can access the application through http://localjobs-domain-name.rhcloud.com. Replace the domain name with your own unique domain name.

The above command creates a standardized MAVEN project template. Interestingly, there is a section of configuration information named OpenShift in the Pom.xml file, as shown below. So when you push your source code to OpenShift, the MAVEN configuration file is executed. The profile does not cause any impact--it simply creates a war file named Root, which guarantees that our application can be used against the root background.

OpenShift localjobs Maven-war-plugin 2.1.1 Deployments ROOT

Next, we will remove the index.html and snoop.jsp two files from their Git libraries-their historical mission is complete. If you are not familiar with how git works, please click here to read the hands-on guide written by Lars Vogel.

git rm-f src/main/webapp/index.html src/main/webapp/snoop.jsp

git commit-am "deleted template Files"

Add MongoDB Java driver affinity

The Pom.xml file created by OpenShift already has all the affinity associated with Java EE 6. To use MongoDB, we also need to add MongoDB Java driver affinity. I'm using the latest version of the MongoDB Java driver. Add the following associated content to the Pom.xml file. You can click here to view the complete Pom.xml file on the GitHub.

Org.mongodb Mongo-java-driver 2.10.1

Enable CDI

CDI represents the background and relevance of injection. CDI is used in applications because we need to use the affinity injection instead of creating objects manually. The CDI container manages the bean lifecycle so that we as developers only need to write business logic. In order for the JBOSSEAP application server to understand that we are using CDI, we need to create a beans.xml file under the Inf folder. The file can remain blank, but its presence will make the container aware of the need to load the CDI framework. The contents of the Beans.xml file are as follows:

Sun.com/xml/ns/javaee "ns =" Http://java.sun.com/xml/ns/javaee "/>

Writing Mongdb Database connection classes

Next, we will create an application scoping bean to manage the MongoDB database connection. The connection class also works on both the local system and the OpenShift side. You can click here to view the full contents of the class in GitHub.

@ApplicationScoped public class DbConnection {private DB mongoDB; @PostConstruct public void aftercreate () { SYSTEM.OUT.PRINTLN ("Ethically if we can dour anything"); String host = system.getenv ("Openshift_mongodb_db_host"); if (host = null | | '. Equals (host) {//Create local MongoDB Connection} else {String mongoport = system.getenv ("Openshift_mongodb_db_port" ); String user = system.getenv ("Openshift_mongodb_db_username"); String Password = system.getenv ("Openshift_mongodb_db_password"); String db = system.getenv ("Openshift_app_name"); int port = Integer.decode (Mongoport); Mongo Mongo = null; try {MONGO = new MONGO (host, Port), catch (Unknownhostexception e) {System.out.println ("couldn ' t connect to MONGO:" + E.getmessage () + "::" + e.getclass ()); MongoDB = MONGO.GETDB (db); if (mongodb.authenticate (user, Password.tochararray ()) = = False) {System.out.println ("Failed to authenticate DB");}} @Produces public DB Getdb () {return MongoDB}}

The @ApplicationScoped bean will always exist while the application is running and is deleted while the application is shutting down. This is exactly the connection pool object retention effect that we want to achieve through the MongoDB drive.

Writing restful backend

Now we're starting to use Jax to write the restful backend for our applications. We will activate Jax by creating a class to extend the Javax.ws.rs.ApplicationPath. You need to specify a base URL and use it as the access address for the network service. To do this, we need to annotate this class with the Applicationpath annotation. As shown in the following code, I use "API" as the underlying URL:

Import Javax.ws.rs.ApplicationPath; Import javax.ws.rs.core.Application; @ApplicationPath ("API") public class Jaxrsactivator extends Creator {/* class body intentionally left blank/}

After successfully activating Jax, we can now write our own rest service. You can access http://localjobs-domain-name/api/jobs/{skills}?longitude={longitude}&latitude={latitude} to view the rest endpoint. The rest endpoint searches for all jobs that match the job-seekers ' skills within the perimeter latitude and longitude.

@Path ("/jobs") public class Jobsrestservice {@Inject private db db; @GET @Path ("/{skills}") @Produces ( Mediatype.application_json) public List Alljobsneartolocationwithskill (@PathParam ("skills") String skills, @ Queryparam ("longitude") double longitude, @QueryParam ("latitude") double latitude) {string] Skillsarr = Skills.split (" ,"); Basicdbobject cmd = new Basicdbobject (); Cmd.put ("Geonear", "Jobs"); Double lnglat[] = {longitude, latitude}; Cmd.put ("near", Lnglat); Cmd.put ("num", 10); Basicdbobject skillsquery = new Basicdbobject (); Skillsquery.put ("Skills", New Basicdbobject ("$in", Arrays.aslist (Skillsarr)); Cmd.put ("Query", skillsquery); Cmd.put ("Distancemultiplier", 111); Commandresult Commandresult = Db.command (cmd); Basicdblist results = (basicdblist) commandresult.get ("results"); List jobs = new ArrayList (); for (Object obj:results) {Job job = new Job (basicdbobject) obj); Jobs.add (Job); } }

The code shown above creates a query near the MongoDB, with the resulting number of files being limited to 10. The result returned by MongoDB will be the numeric value in the data. Because we use longitude and latitude to locate, the returned data is also based on latitude and longitude. However, MongoDB also offers a set of distance-changing options that allow us to convert the latitude and longitude results into more comprehensible kilometres or miles. In the code above, I converted the latitude and longitude results to 111 kilometers. Finally, we convert the data to a domain object named job and return it. @Produces Note will be responsible for converting the data into JSON.

Load data into MongoDB

Execute the following command to load the data into the MongoDB running in openshift gear.

On the local device, run RHC app show. This command returns the details of the application, as follows:

$ RHC App show-a localjobs localjobs @ http://localjobs-newideas.rhcloud.com/(uuid:5195d8fe5973ca386f000083)--------- --------------------------------------------------------------------------created:12:45 PM gears:1 (defaults to Sgt Git Url:ssh://5195d8fe5973ca386f000083@localjobs-newideas.rhcloud.com/~/git/localjobs.git/ssh: 5195d8fe5973ca386f000083@localjobs-newideas.rhcloud.com jbosseap-6.0 (JBoss Enterprise creator Platform 6.0)---- ----------------------------------------------------gears:located with mongodb-2.2 mongodb-2.2 (MongoDB NoSQL Database 2.2)----------------------------------------gears:located with jbosseap-6.0 Connection url:mongodb://$ Openshift_mongodb_db_host: $OPENSHIFT _mongodb_db_port/database name:localjobs password:qysukkdkrzqt username:admin

Record the SSH URL and use the SCP command to copy the Jobs-data.json file into our application gear. You can click here to download the Jobs-data.json file.

$ SCP Jobs-data.json:app-root/data

Then insert SSH into the application, using the RHC app SSH command as shown below:

$ RHC App Ssh-a Localjobs

After importing SSH into the application gear, change the directory to App-root/data, which is the directory where we copy jobs-data.json files.

$ CD App-root/data

The following runs the Mongoimport command to import data into the MongoDB database.

$ mongoimport-d localjobs-c Jobs--file jobs data.json-u $OPENSHIFT _mongodb_db_username-p $OPENSHIFT _mongodb_db_ Password-h $OPENSHIFT _mongodb_db_host-port $OPENSHIFT _mongodb_db_port

The code shown above will import 159 job objects into the MongoDB.

Finally, we need to create a geographical index in our work collection. MongoDB only supports a two-dimensional geographical index. You can only match a set of geographical indexes for each collection. By default, a two-dimensional geographic index assumes longitude and latitude values between 180 (including 180) to 180 (excluding 180) (that is, [-180,180]). To create a geographic information index, you need to perform the following commands:

$ MONGO $ use Localjobs $ db.jobs.ensureIndex ({"Location": "2d"})

Testing RESTful Services

Below, we will provide the source code and push the change to OpenShift, that is, create the project, create a new war file, and deploy it to the jbosseap running on OpenShift.

$ git Add. $ git commit-am "resful backend Done" $ git push

Once the code creation and war file deployment is complete, we can use the Curl command to test the rest service.

Curl-i-H "Accept:application/json" http://localjobs-newideas.rhcloud.com/api/jobs/java,scala?longitude=- 121.894955&latitude=37.339386 http/1.1 OK Date:fri, May 2013 08:39:11 GMT server:apache-coyote/1.1 Content-type:application/json vary:accept-encoding transfer-encoding:chunked [{"CompanyName": "Cybercoders", " JobTitle ":" Embedded Java Applications Engineer "," Distance ": 4153.025944882882," skills ": [" Java "]," formattedaddress " : "1400 North Shoreline Boulevard, Kings View, CA, United States", "Longitude": -122.078488, "latitude": 37.414198},{" CompanyName ":" Cybercoders "," JobTitle ":" Embedded Java Applications Engineer "," Distance ": 4153.025944882882," skills " : ["Java"], "formattedaddress": "1400 North Shoreline Boulevard, Kings View, CA, United States", "Longitude":- 122.078488, "latitude": 37.414198} ...

Landscaping Applications

Now that we have confirmed that the rest of the application is working properly, the next step is to build the user interface for the application. In this article, we just need to create a very simple application user interface, that is, to provide a set of forms that users can use to enter their personal skills, and through the Div hosting Google Map rendering completed job site and user location. Create a index.html file in the Src/main/webapp folder as follows:

Related Article

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.