Categories: ProgrammingTutorials

Posting Reviews, Ratings, and Photos

15 min read

In this article, by Hussein Nasser, the author of the book Building Web Applications with ArcGIS, we will learn how to perform editing on services by adding three features, posting reviews, ratings, and uploading pictures for the restaurant.

(For more resources related to this topic, see here.)

Configuring enterprise Geodatabase

Unfortunately, editing process requires some more configurations to be done, and the current service, wouldn’t do the trick. The reason is that the service is using a local database file; however, editing GIS data on the Web requires either an enterprise database running on a database management server such as the SQL server, or Oracle, or an ArcGIS Online feature service. Setting up the enterprise geodatabase server is out of the scope of this book. However, you can grab my book Learning ArcGIS Geodatabase, Packt Publishing, and walk through the step-by-step full guide to set up your own enterprise geodatabase with Microsoft SQL Server Express. If you have an existing enterprise geodatabase server, you can use it. I will be using SQL Server Express 2012 SP1.

Connecting to the Geodatabase

First, we need to establish a connection to the enterprise server. For that we will use a username that has full editing capabilities. I will be using the system administrator (SA) user sa for the SQL server.

Note that the SA user has full access to the database; we have used it in this book for simplicity to avoid assigning privileges. In an ideal situation, you would create a user and assign him the correct permissions to read or write into the subject tables. My book, Learning ArcGIS Geodatabase, Packt Publishing, addresses all these issues thoroughly.

Follow these steps to establish a connection to your enterprise geodatabase:

  1. Open ArcCatalog and expand Database Connections in the Catalog Tree panel.
  2. Double-click on Add Database Connection.
  3. In the Database Platform option select SQL Server (or your database provider).
  4. Type the name of the server hosting the database; in my case, it is the same server arcgismachine.
  5. Select Database authentication in Authentication Type and provide the database credentials for the sa user or any user who has administrator privileges on the database. You can use the SDE user as well.
  6. Select your Database from the drop-down list and click on OK as shown in the following screenshot:
  7. Rename the connection to sa@arcgismachine.sde. We are going to reference this later in the article. Don’t close ArcCatalog yet, we will be needing it.

You can learn more about ArcGIS database connections and how to create them against different databases from the link http://qr.net/arcgisdb.

Copying Bestaurants’ data to the server

Now that we have our connection ready, we need to copy the Bestaurants data into our new database. Follow these steps:

  1. From Catalog Tree, right-click on the Folder connection and select Connect to Folder. Browse to C:2955OT, the folder we created in the book Building Web Application with ArcGIS, and click on OK. This will allow us to access our Bestaurants data.
  2. From Folder Connection, expand C:2955OT and browse to 2955OT_01_FilesBestaurants.gdb.
  3. Click on Bestaurants.gdb, use the Shift key to select Belize_Landbase and Food_and_Drinks. Then right-click and select Copy as shown in the following screenshot:
  4. Double-click on the ags@arcgismachine.sde connection to open it. Right-click on the connection and select Paste. You will be prompted with the following dialog box that will show you what will be copied. Note that related data was also imported. This will paste the data to our new database.
  5. After the copying is completed, close ArcCatalog.

Publishing feature service

Our old service won’t work in this article; the reason is that it was pointing to a local database which does not support editing on ArcGIS for Server. That is why we migrated our Bestaurants data to the enterprise geodatabase. It is time to publish a brand new service; it will look the same but will just behave differently. First, we need to open our Belize.mxd map document and point our new database. Second, we will register the database with ArcGIS for Server; finally, we will publish the service.

Setting the Source to the Enterprise Geodatabase

In order to publish the new service, we have to first create a map document which points to the enterprise geodatabase. Follow these steps to do so:

  1. Browse to and open 2955OT_05_FilesBelize.mxd with ArcMap. You can simply double-click on the file.
  2. Next, we set the source of our layers from the Table of Contents in ArcMap. Click on List by Source as shown in this screenshot:
  3. Double-click on the Food_and_Drinks layer to open the Layer properties.
  4. In the Layer Properties window, click on Set Data Source.
  5. From the Data Source dialog, browse to the sa@arcgismachine.sde connection and select the sdedb.DBO.Food_and_Drinks object, and then click on Add as illustrated in this screenshot:
  6. Click OK to apply the changes.
  7. Do the same for the rest of the objects, Landbase and VENUES_REVIEW, in your map selecting the matching objects in the destination connection.
  8. The final source list should look like the following, nothing pointing to the local data. Keep ArcMap open for the next step.

You can also modify the data sources in an ArcMap document using ArcCatalog.

In ArcCatalog, navigate to the map document in Catalog Tree, right-click on the map document, and choose the Set Data Sources option from the pop-up menu. Using this allows you to set the data source for individual and/or all layers at one time.

Publishing the map document

Now that we have our map document ready, it is time for us to publish it. However, we still need to perform one more step, which is database registration. This step will cause the data to persist in the server, which makes it ready for editing. Follow these steps to publish the map document:

  1. From the File menu, point to Share As and click on Service.
  2. Select Overwrite an existing service, because we want to replace our old Bestaurants service. Click on Next.
  3. Select the Bestaurants service and click on Continue.
  4. From the Service Editor window, click on Capabilities.
  5. Check the Feature Access capability to enable editing on this service as shown in the following screenshot:
  6. Click on Analyze. This will show an error that we have to fix. The error is Feature service requires a registered database. This error can be solved by right-clicking on it and selecting Show Data Store Registration Page, as shown in the following screenshot:
  7. In the Data Store window, click on the plus sign to add a new database.
  8. In the Register Database window, enter in Bestaurants in the Name textbox.
  9. Click on Import and select the sa@arcgismachine connection. Make sure the Same as publisher database connection option is checked as shown in the following screenshot:
  10. Click on OK in the Register Database window and the Data Store window.
  11. Click on Analyse again; this time you shouldn’t get any errors. Go ahead and Publish your service.
  12. Close ArcMap.

    You can read more about registering databases at: http://qr.net/registerdb.

Testing the web application with the new service

We have updated our Bestaurants service, but it should work fine so far. Hence, just make sure that we run your application under http://arcgismachine/mybestaurants.html.

You can find the latest code at 2955OT_05_FilesCodebestaurants01_beforeediting.html, copy it to c:inetpubwwwroot and rename it accordingly.

Adding ArcGIS’s editing capabilities

Currently, the food and drinks layer is being fetched as a read-only map service located at the URL: http://arcgismachine:6080/arcgis/rest/services/Bestaurants/MapServer/0. The only difference is that it points to the enterprise geodatabase. You can see the following code in mybestaurants.html which confirms that:

//load the food and drinks layer into an object
lyr_foodanddrinks = new esri.layers.FeatureLayer
("http://arcgismachine:6080/arcgis/rest/
services/Bestaurants/MapServer/0", { outFields: ["*"] }
);

We won’t be able to edit MapServerlayer, we have to use FeatureServer. We will show how to change this in the next section.

Adding or updating records in a service with ArcGIS JavaScript API is simple. We only need to use the applyEdits method on the FeatureLayer object. This method accepts a record and some parameters for the response; what we are interested in is to insert a record. The following code shows how to prepare a record with three fields for this function:

varnewrecord = 
{
attributes:
{
   FIELD1: VALUE1,
   FIELD2: VALUE2,
   FIELD3: VALUE3
}
};

For instance, if I want to create a new record that has rating and review, I populate them as follows:

varnewrecord = 
{
attributes:
{
   REVIEW: "This is a sample review",
   RATING: 2,
   USER: "Hussein"
}
};

And to add this record, we simply call applyEdits on the corresponding layer and pass the newrecord object as shown in the following code snippet:

var layer = new esri.layers.FeatureLayer("URL");
layer.applyEdits([newrecord], null, null, null, null);

Posting reviews and ratings

The first thing we have to add is to point our food and drinks layer to its feature server instead of the map server to allow editing. This can be achieved by using the following URL instead, simply replace MapServer with FeatureServer:

http://arcgismachine:6080/arcgis/rest/services/Bestaurants/FeatureServer/0

Follow these steps to perform the first change towards editing our service:

  1. Edit mybestaurants.html. Find the food and drinks layer initialization and point it to the feature service instead using the following code snippet:
    //load the food and drinks layer into an object
    lyr_foodanddrinks = new
    esri.layers.FeatureLayer
    ("http://arcgismachine:6080/arcgis/rest/services
    /Bestaurants/FeatureServer/0", { outFields: ["*"] }
    );
  2. The review and rating fields can be found in the VENUES_REVIEW table. So we can add a single record that has a review and a rating, and send it to the service. However, we need to prepare the necessary controls that will eventually populate and add a record to the reviews table. Let’s modify the ShowResults function of our query so that each restaurant shows two textboxes: one for review and one for the rating. We will also add a button so that we can call the addnewreview()function that will add the review. Each control will be identified with the object ID of the restaurant as shown in the following code:
    //display the reating
    resulthtml = resulthtml + "<b>Rating:</b> " +
    record.attributes["RATING"];
    //create a place holder for each review to be populated later
    resulthtml = resulthtml + "<div id = 'review" +
    record.attributes["OBJECTID"] + "'></div>";
    //create a place holder for each attachment picture to be populated later
    resulthtml = resulthtml + "<div id = 'picture" +
    record.attributes["OBJECTID"] + "'></div>";
    //create text box for the review marked with the objectid
    resulthtml = resulthtml + "<br>Review: <input type = 'text' id
    = 'txtreview" + record.attributes["OBJECTID"] + "'>";

    //another one for the rating.
    resulthtml = resulthtml + "<br>Rating: <input type = 'text' id
    = 'txtrating" + record.attributes["OBJECTID"] + "'>";

    //and a button to call the function addnewreview
    resulthtml = resulthtml + "<br><input type = 'button' value =
    'Add' onclick = 'addnewreview(" +
    record.attributes["OBJECTID"] + ")'>";
  3. Now, we need to write the addnewreview function. This function accepts an object ID and adds a record matching that object to the reviews table. I have placed the three empty variables: object ID, review, and rating, and prepared the template to write a new record. I also created a feature layer of our VENUES_REVIEW table:
    functionaddnewreview(oid)
    {
    varobjectid;
    var review;
    var rating;
    varnewReview =
    {
       attributes:
       {
         VENUE_OBJECTID: objectid,
         REVIEW: review,
         RATING: rating
       }
    };
    //open the review table
    varreviewtable = new esri.layers.FeatureLayer
    ("http://arcgismachine:6080/arcgis/rest/services
    /Bestaurants/FeatureServer/2");
    //apply edits and pass the review record
    reviewtable.applyEdits([newReview], null, null, null, null);
    }
  4. You might have guessed how to obtain the review, rating, and object ID. The object ID is passed, so that is easy. The review can be obtained by searching for txtreview + objectid. A similar search can be used for rating. Let’s also add a message to see if things went fine:
    functionaddnewreview(oid)
    {
    varobjectid = oid;
    var review =document.getElementById('txtreview' +
       oid).value;
    var rating = document.getElementById('txtrating' +
       oid).value;
    varnewReview =
    {
       attributes:
       {
         VENUE_OBJECTID: objectid,
         REVIEW: review,
         RATING: rating
       }
    };
    //open the review table
    varreviewtable = new esri.layers.FeatureLayer
       ("http://arcgismachine:6080/arcgis/rest/services
       /Bestaurants/FeatureServer/2");
    //apply edits and pass the review record
    reviewtable.applyEdits([newReview], null, null,
       null, null);
    alert("Review has been added");
    }
  5. You can also add the user to your record in a similar way:
    varnewReview =
    {
    attributes:
       OBJECTID: objectid,
       REVIEW: review,
       USER_: "Hussein"
       RATING: rating
    }
    };
  6. It is time for us to save and run our new application. Do a search on Fern, then write a review, add a rating, and then click on Add. This should add a record to Fern Diner. You can always check if your record is added or not from ArcCatalog. This can be seen in the following screenshot:

    You can find the latest code at 2955OT_05_FilesCodebestaurants02_addreviews.html.

Uploading pictures

Uploading attachments to a service can be achieved by calling the addAttachment method on the feature layer object. However, we have to make some changes in our ShowResults function to ask the user to browse for a file. For that, we will need to use the file’s HTML object, but we have to encapsulate it in a form tagged by the object ID of the restaurant we want to upload the pictures for. The file object should be named attachment so that the addAttachment method can find it. Follow these steps to add the upload pictures’ logic:

  1. Edit the mybestaurants.html file and add the following code to your ShowResults function:
    //browse for a picture for this restaurant
    resulthtml = resulthtml + "<form id = 'frm" +
    record.attributes["OBJECTID"] + "'><input type =
    'file' name = 'attachment'/></form>";
    //and a button to call the function addnewreview
    resulthtml = resulthtml + "<br>
    <input type = 'button' value = 'Add' onclick =
    'addnewreview(" + record.attributes["OBJECTID"] + ")'>";   
    //new line
    resulthtml = resulthtml + "<br><br>";
  2. We will make it so that when the user clicks on Add, the attachment is also added along with the review for simplicity. The AddAttachment function takes the object ID of the restaurant which you want to upload the picture to, and a form HTML element which contains the file element named attachment:
    functionaddnewreview(oid)
    {
    varobjectid = oid;
    var review = document.getElementById('txtreview' +
       oid).value;
    var rating = document.getElementById('txtrating' +
       oid).value;
    varnewReview =
    {
       attributes:
       {
         VENUE_OBJECTID: objectid,
         USER_: "Hussein",
         REVIEW: review,
         RATING: rating
       }
    };
    //open the review table
    varreviewtable = new esri.layers.FeatureLayer
    ("http://arcgismachine:6080/arcgis/rest/services
       /Bestaurants/FeatureServer/2");
    //apply edits and pass the review record
    reviewtable.applyEdits
       ([newReview], null, null, null, null);
    //add attachment
    lyr_foodanddrinks.addAttachment(oid,
       document.getElementById("frm" + oid) , null, null);
    alert("Review and picture has been added");
    }
  3. Save and run the code. Search for Haulze Restaurant. This one doesn’t have an attachment, so go ahead, write a review, and upload a picture. Run the query again and you should see your picture. This is shown in the following screenshot:

The final code can be found at 2955OT_05_FilesCodebestaurants03_uploadpicture.html.

The final touches

This is where we add some web enhancements to the application, things that you as a web developer can do. We will update the status bar, make part of the page scrollable, change the rating into star icons, and do some fine-tuning of the interface. I have already implemented these changes in the final version of the application, which can be found at 2955OT_05_FilesCodebestaurantsfinal.html. These changes don’t have anything to do with ArcGIS development; it is pure HTML and JavaScript. The final application should look as shown in the following screenshot:

Summary

In this article, we have put the final touches to the Bestaurants ArcGIS web application by adding rating, reviews, and uploading pictures to the ArcGIS service. We have learned that editing can only be done for the feature services on the data hosted on enterprise geodatabases that is why we had to set up our own. We have copied the data to a new server, and modified the source document to point to that server. Then we republished the service with feature-access capability to enable editing. We finally added the necessary JavaScript API code to write reviews and upload pictures to the website. With these features, we have completed the Bestaurants project requirements.

This is the end of this book but it is only the beginning of great potential applications that you will be developing using the skill set you acquired in the course of this journey.

You can now be confident in pursuing more advanced ArcGIS JavaScript APIs from the Esri website (resources.arcgis.com) which is a good place to start. There are hundreds of methods and functions in the API. However, keep in mind that you only need to learn what you really need and require to. We have managed to complete an entire website with a handful of APIs. Take the next project, analyze the requirements, see what APIs you need, and learn them. That is my advice. My inbox is always ready for suggestions and thoughts, and of course, questions.

Resources for Article:


Further resources on this subject:


Packt

Share
Published by
Packt

Recent Posts

Harnessing Tech for Good to Drive Environmental Impact

At Packt, we are always on the lookout for innovative startups that are not only…

2 months ago

Top life hacks for prepping for your IT certification exam

I remember deciding to pursue my first IT certification, the CompTIA A+. I had signed…

3 years ago

Learn Transformers for Natural Language Processing with Denis Rothman

Key takeaways The transformer architecture has proved to be revolutionary in outperforming the classical RNN…

3 years ago

Learning Essential Linux Commands for Navigating the Shell Effectively

Once we learn how to deploy an Ubuntu server, how to manage users, and how…

3 years ago

Clean Coding in Python with Mariano Anaya

Key-takeaways:   Clean code isn’t just a nice thing to have or a luxury in software projects; it's a necessity. If we…

3 years ago

Exploring Forms in Angular – types, benefits and differences   

While developing a web application, or setting dynamic pages and meta tags we need to deal with…

3 years ago