Retrieve markers from the database and display them as a layer that can be easily togg

I am currently working on integrating custom markers from a database into my Google map. While I have successfully loaded KML layers, I aim to allow users to save and load their personalized markers stored in the database.

The structure of my database is as follows:

| ID | TITLE | LAT | LON |

Considering that each user will have their own set of custom points, my goal is to retrieve these points and display them as a layer on the map alongside other default layers (KML). I have learned that creating a data layer, along with using geoJSON, would be the most efficient approach. However, I am still in the process of figuring out how to generate geoJSON from my database.

At the moment, I am utilizing a generic JSON file to test if I can incorporate it as a toggleable layer, but I am facing some difficulties. Once I manage to resolve this issue, I plan to extract the data from the database, format it in geoJSON, and integrate it into the map.

Here is an excerpt of my attempt to incorporate JSON data as a toggleable layer, albeit unsuccessfully:

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -49.7770641, lng: 55.6602758},
    zoom: 6,
    mapTypeControlOptions: {
         position: google.maps.ControlPosition.RIGHT_TOP
      },

  });

    layers[0] = new google.maps.KmlLayer('http://www.example.com/kmllayer1.kml', {preserveViewport: true, suppressInfoWindows: false, zIndex: 1});
    layers[1] = new google.maps.KmlLayer('http://www.example.com/kmllayer2.kml', {preserveViewport: true, zIndex: 2, suppressInfoWindows: true});
    layers[2] = map.data.loadGeoJson('https://storage.googleapis.com/maps-devrel/google.json');
    for (var i = 0; i < layers.length; i++) {
        layers[i].setMap(map);
      }
}
function toggleLayer(i) {
      if(layers[i].getMap() === null) {
        layers[i].setMap(map);
      }
      else {
        layers[i].setMap(null);
      }
    }

Answer №1

When working with the data layer in Google Maps JavaScript API, it is important to note that it differs from the KmlLayer. The .loadGeoJson method of the data layer returns an array of Data.Feature objects. According to the API documentation:

addGeoJson(geoJson:Object, options?:Data.GeoJsonOptions)

Return Value: Array<Data.Feature>

This method adds GeoJSON features to the data layer collection. By providing parsed JSON data to this method, the imported features are then returned. An exception is thrown if the GeoJSON data cannot be imported.

To integrate GeoJSON data into your map, you can follow this simple step (assuming you have only one layer):

layers[2] = map.data;
layers[2].loadGeoJson(GEOJSON_URL);

For a demonstration, you can check out this proof of concept fiddle.

Here is a snippet of the code:


var geocoder;
var map;
var layers = [];

function toggleLayer(i) {
  if (layers[i].getMap() === null) {
    layers[i].setMap(map);
  } else {
    layers[i].setMap(null);
  }
}

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 43,
      lng: -87
    },
    zoom: 4,
    mapTypeControlOptions: {
      position: google.maps.ControlPosition.RIGHT_TOP
    }
  });

  layers[0] = new google.maps.KmlLayer('http://googlemaps.github.io/js-v2-samples/ggeoxml/cta.kml', {
    preserveViewport: true,
    suppressInfoWindows: false,
    zIndex: 2
  });
  layers[1] = new google.maps.KmlLayer('https://developers.google.com/kml/documentation/us_states.kml', {
    preserveViewport: true,
    zIndex: 1,
    suppressInfoWindows: true
  });
  layers[2] = map.data;
  layers[2].loadGeoJson('http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojson');
  for (var i = 0; i < layers.length; i++) {
    layers[i].setMap(map);
  }
  var btns = document.getElementsByClassName("btn");
  for (var i = 0; i < btns.length; i++) {
    google.maps.event.addDomListener(btns[i], 'click', (function(i) {
      return function() {
        toggleLayer(i);
      }
    })(i));
  }
}

google.maps.event.addDomListener(window, "load", initMap);

html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px;
}

<script src="https://maps.googleapis.com/maps/api/js"></script>
<input class="btn" id="btn0" type="button" value="0" />
<input class="btn" id="btn1" type="button" value="1" />
<input class="btn" id="btn2" type="button" value="2" />
<div id="map"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add the item to a fresh array using the Ajax function

Here is an array that I have: var arrayOfResults = []; // Results after like statement After making a database call, I receive a JSON result like this: [{ "id": "{fcb42c9c-3617-4048-b2a0-2600775a4c34}", "pid": "{34214CCB-90C3-4D ...

Locate the highest and lowest values within a .json file

When working on a graph using d3.js, one key step is setting up the scales for the axis. The data for the graph is stored in a Json file with multiple arrays, each representing different regions and years: [{ "id" : "AustraliaNewZealand" , "year" ...

Utilizing the `theme` property in makeStyles with Material-UI

I am currently working on passing down an muiTheme to a component through the use of ThemeProvider, and I also want to apply it to the children components. Furthermore, I aim to utilize the theme's properties in both components by creating a classes o ...

The Java JSON parser encountered an unanticipated character (i) at the beginning of the input

{ "0" : { "upc" : "00000000005", "name" : "Weighable Soup Cups", "location" : "5310ed21d5dc7aaa0343a932" }, "1" : { "upc" : "00000000011", "name" : "OF Reuseable Bags", "location" : "5310ed21d5dc7 ...

Unexpected issue encountered while working with json, ajax, and jQuery

Here's the code snippet that I'm working with: $.ajax({type: 'get', mode: 'abort', dataType: 'json', url: 'http://localhost/1.php', data: {}, success: function(res){ alert(res); }, time ...

transfer the value of a method to a different component

In my Component called IncomeList, there is a method named sumValue. This method simply adds different numbers together to produce one value, for example 3+5 = 8. Similarly, in another Component named OutputList, the same logic is applied but with a method ...

What is the most effective way to iterate through an array of objects and retrieve the results in a key-value format?

I am dealing with an array of objects that may seem a bit complex initially, but I will simplify it as much as possible. Each object in the array has properties like Engineering, Environment, and others, each containing a sub-object called radars. The rada ...

Compare object key and array in Javascript to create a new object

Can you aid me in achieving the following output by comparing var1 and var2, and obtaining the output based on var2 where the keys are provided in a string array? var1 = {a:1, b:2, c:3, d:4}; var2 = ['a', 'd']; The expected output is ...

Guide on how to display a partial view in a controller using Json

Is there a way to incorporate a partial view into a JsonResult within a controller? return Json(new { Html = this.RenderPartialView("_EditMovie", updatedMovie), Message = message }, JsonRequestBehavior.AllowGet); ...

Enable automatic full-screen mode on Google Chrome upon page load

I would greatly appreciate it if you could provide an answer to this question, even if it is marked as a duplicate. I have tried various solutions and sought help, but unfortunately, nothing seems to be working for me... What I really need is for the brow ...

how to conceal an image using its icon attribute

Hello everyone, I've been searching for a solution to my question online but couldn't find one. I am looking to hide images based on their icon-value attribute. For example, I want to hide the image with icon-value="1" within the div that has a c ...

Connecting script.js with html file

I am attempting to connect the script.js file to my HTML in order to incorporate interactive features on the page. The goal was to change the image of door1 when it is clicked on, but it doesn't seem to be working. Any feedback on this issue would be ...

Eliminate server-side functionality from the React project's boilerplate template

After cloning and installing the project from https://github.com/react-boilerplate/react-boilerplate, I realized that I only need the client-side portion as I intend to use a pre-existing server (express) for my application setup. Below is an excerpt f ...

Managing waste: AngularJS service variable cleanup

I am a beginner in angularjs. Recently, I created an angularJS service based on the following diagram: https://i.sstatic.net/NifC5.png The Global Service acts as a way for controllers to communicate with each other. It holds data shared between parent an ...

the conditional operator used without assigning the result to a variable

Exploring conditional operators on html canvas, I am seeking a streamlined approach to dynamically change stroke color based on conditions. Online examples have not provided a satisfactory solution in a single line of code. Currently, without using a cond ...

"Streamlining data entry with an uncomplicated HTML form input that accepts multiple values from a

As I understand it, a barcode scanner functions as nothing more than a keyboard that transmits keycode 13 after each scan. My task is straightforward: I have a basic form with only one input field and I want the ability to scan numerous barcodes and then c ...

Creating PHP functions that return a JSON string when invoked - a simple guide

I have created a script that contains various functionalities, including fetching data from a database and encoding it into JSON. However, I want to be able to call different functions to execute these scripts separately. When I attempted to define and c ...

Filtering in AngularJS seems to only work in one direction

I am working on implementing two different ways of filtering data - one by clicking on letters and the other by typing in an input field. <body ng-controller="MainController"> <ul search-list=".letter" model="search"> <li class= ...

The Camel Cased JSON configuration for the Web API appears to be malfunctioning

Within my WebApiConfig.cs file and the Register method, I have the following code: var jsonFormatter=config.Formatters.JsonFormatter; jsonFormatter.UseDataContractJsonSerializer = false; jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePro ...

When clicking in JavaScript, there are two parts to the function, however only one part will work at any given time

I am currently working with two server-side PHP scripts: 1. /addit.php - which generates a PDF file on the server based on the provided ID 2. /viewit.php - which allows the PDF file to be downloaded to the browser window. While both of these scripts are ...