Create a KML layer on a Google Map by uploading from a text input field

Is there a way to use the javascript api to draw a kml layer on a google map by copying the kml code from a textarea, similar to how it can be done on this page?

Most examples in the documentation I found demonstrate loading the kml layer from a file.

Answer №1

Check out this example, it showcases the use of the geoxml3 third-party KML parser along with another library for editing KML files.

For a working fiddle demonstration, you can refer to this link.

Here's a snippet of the code provided:

var geocoder;
var map;

// More JavaScript code snippets go here...
html,
body,
#map_canvas {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
You'll need to include the following scripts in your HTML file: - Google Maps API script - geoxml3.js script - ProjectedOverlay.js script In addition, make sure to add a div element with an id of "map_canvas" to display the map and an input button to trigger the parsing of KML to the map. Feel free to explore the full code provided above!

Answer №2

One way to approach this is by converting kml files to GeoJSON format and utilizing the Data Layer feature instead of directly using Google Maps API. You can achieve this by employing the toGeoJSON library provided by Mapbox, which offers additional functionalities.

An important point to note is that toGeoJSON does not support kmz format, hence you would need to extract the file before processing it. In my experience, I had to adjust the kml polygon as toGeoJSON requires closed polygons with the same first and last coordinate for proper functioning.

To further explore the implementation, you can refer to the code available in this Fiddle link.

//initialize infoWindow object
var infWindow = new google.maps.InfoWindow();

function setMapFromKML(kmlString) {
  if (kmlString.length == 0) {
    return false;
  }
  if (typeof toGeoJSON == "undefined") { 
    alert("toGeoJSON.js not included");
    return;
  }
  
  var domparser = new DOMParser();
  var kml = domparser.parseFromString(kmlString, "text/xml");

  var geojson = toGeoJSON.kml(kml);

  var features = map.data.addGeoJson(geojson);

  var bounds = new google.maps.LatLngBounds();

  features.forEach(function(feature) {

    feature.getGeometry().forEachLatLng(function(latlng) {
      bounds.extend(latlng);
    });

  });

  map.fitBounds(bounds);

  map.data.addListener('click', function(event) {
    var infContent = GetContent(event);
    var latlng;
    if (typeof event.feature.getGeometry().get !== "undefined") { //for point
      latlng = event.feature.getGeometry().get();
    } else { //polygon/multi,etc...
      var polybounds = new google.maps.LatLngBounds()
      event.feature.getGeometry().forEachLatLng(function(featurelatlng) {
        polybounds.extend(featurelatlng);
      });

      latlng = polybounds.getCenter();
    }

    openInfowindow(latlng, infContent);

  });

}

function GetContent(event) {
  var content = '<div><h3>' + event.feature.getProperty('name') + '</h3>' + event.feature.getGeometry().
  getType() + '<br></div>';
  return content;
}

function openInfowindow(latLng, content) {
  var div = document.createElement('div');
  div.innerHTML = content;

  infWindow.setContent(div);
  infWindow.setPosition(latLng);
  infWindow.open(map);
}

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

Facing difficulties in Angular 8 while trying to import firestore and firebase for an authentication system

While attempting to implement Firestore/Firebase functionalities for Google OAuth signin, I encountered an error indicating that Firebase is not imported: https://i.sstatic.net/oL4rY.png CODE: ERROR in node_modules/@angular/fire/auth/auth.d.ts:4:28 - er ...

Creating a single Vuetify expansion panel: A step-by-step guide

Is there a way to modify the Vuetify expansion panel so that only one panel can be open at a time? Currently, all panels can be closed which is causing issues. I would like the last opened panel to remain open. I also want to prevent closing the currently ...

What is the best way to incorporate an image zoom-in effect into a flexible-sized block?

Having a fluid grid with 3 blocks in one row, each set to width:33.3%. The images within these blocks are set to width: 100% and height: auto. I am looking to implement a zoom-in effect on hover for these images without changing the height of the blocks. I ...

transferring JSON information to a template in a NodeJs application

Currently, I am performing some filtering on my JSON data and storing the result in a variable called driver. The driver variable contains JSON data that I want to pass unchanged to the view. My main query is: How can I effectively send the data stored i ...

Why does the AngularJS ngRepeat filter permanently remove null values?

Check out this JSFiddle demonstration I created to illustrate the problem: http://jsfiddle.net/s6Lj2/2/ Observe that in the dataset $scope.places = [{ name: 'Chicago', status: 'Active', analyst: 'Sam', recor ...

A tutorial on making a POST request using axios in a React application

I am struggling with my JavaScript skills I need assistance with calling the following CURL command successfully: curl -X POST -H "Content-Type: application/json" -u john.doe:moqui -d "{\"firstName\":\"Hung&bso ...

What is the best method to ensure that none of the select option values are left empty?

I have a total of 5 select option drop down menus currently, but this number may increase in the future depending on requirements. The issue I'm facing is that when I select the last element, it returns true even though the other elements are empty. I ...

Change the position of a Div by clicking on a different Div using JQuery for custom movements

I have successfully managed to slide the div left/right based on the answers below, but I am encountering some issues with the top div. Here are the specific changes I am looking to make: 1. Make both brown lines thinner without affecting the animations. ...

VueD3tree successfully fetches data, however, it is not being displayed on the screen

Just started delving into Vue and VueD3tree. Attempting to display a tree using the vued3tree library with data pulled from an API. Strangely enough, when trying with static data, the tree displays perfectly fine. However, when fetching data dynamically, a ...

Require a v-alert notification to appear on every page, ensuring visibility across the site

Imagine a scenario where there is a right drawer that displays a grade dropdown with options like grade1, grade2, and grade3. On all pages, I need a v-alert notification strip to show the total count of students. For example, if I select grade3 from the ri ...

Requesting CORs on Web API version 2.0

After enabling CORs on a Web API, I encountered an issue where GET and POST requests were failing on Chrome. Interestingly, the GET request worked fine on MS Edge, but the POST request threw two error messages in the console: The request could not be proc ...

What setting should I adjust in order to modify the color in question?

Looking to Customize Radar Chart Highlighted Line Colors https://i.sstatic.net/PqWc4.png I am currently working on a Radar Chart and I am trying to figure out which property needs to be edited in order to change the color of the highlighted lines. I have ...

PHP/MySQL clarification regarding time slots

Could someone assist me with this discussion I found? Due to my low reputation, I am unable to comment for further clarification. Although I grasp the solution provided in the mentioned discussion, I am struggling to comprehend how to pass the data to my ...

Struggling to retrieve the fake JavaScript data for my Vue.js table

I am a beginner in the development field and encountering the following error report while working with Vue.js 3 115:5 error 'vendorTable' is assigned a value but never used no-unused-vars 115:23 error 'Vue' is not defined no- ...

Guide to managing .glb model animations in A-FRAME using Three.js

Can someone assist me with playing a glb animation in A-FRAME using Three.js? The animation works for a second and then stops. Here is my current code: <script src="https://aframe.io/releases/1.3.0/aframe.min.js"></script> <scrip ...

The replacement of classes in ReactJS using JavaScript seems to be malfunctioning

I have been attempting to change the class of a dynamic element when clicked, but none of my solutions seem to be working. Here is what I have tried: handleClick=(event,headerText)=>{ document.getElementsByClassName('sk-reset-filters') ...

What is the formula to determine if x is greater than y and also less than z?

I need help determining if a number falls within the range of greater than 0 but less than 8 using JavaScript. Can anyone assist me with this? Here is my attempt at it: if (score > 0 && score < 8) { alert(score); } ...

Ensure that scripts with the type of "module" are completed before proceeding to execute the following script

In my HTML document, I have two script tags with type="module" at the bottom of the body tag. Following those, there is another script tag with embedded code that relies on the results of the first two scripts. Is there a method to ensure that this code ...

How can I pass a dynamic scope variable to a JavaScript function in AngularJS that is being updated within an ng-repeat loop?

In my HTML, I have an ng-repeat loop where a variable is displayed in table rows. I want the user to be able to click on a value and pass it to a JavaScript function for further action. The code snippet below showcases my earlier version which successful ...

Utilizing modal functionality for seamless integration of new data into mui-datatable

When trying to add a new data entry using a modal box, I encountered an issue where the new data was not being added to the datatable. Is there a solution for this problem? Below is the code snippet I used: let id = 0; function createData(name, provider) ...