Home > Enterprise >  How to display in Google Maps polygon coordinates stored as string?
How to display in Google Maps polygon coordinates stored as string?

Time:09-29

I have a string of coordinates stored in my MySQL DB which I am not able to display in Google Maps because it requires to be a LatLng object:

'(55.46701996570562, 11.983202375732418),(55.46604683879285, 11.982086576782223),(55.465316977846335, 11.983803190551754),(55.465900867684354, 11.985863127075191)'

I understand I can store these coordinates as POLYGON data type but I dont want to do that due to some other reasons (not relevant to mention them here).

When trying to use that string of coordinates in the below code it shows an error:

const polygon_coords = '(55.46701996570562, 11.983202375732418),(55.46604683879285, 11.982086576782223),(55.465316977846335, 11.983803190551754),(55.465900867684354, 11.985863127075191)';

const coords = new google.maps.Polygon({
    paths: polygon_coords,
    strokeColor: "#FF0000",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#FF0000",
    fillOpacity: 0.35,
    editable: true
});

Error:

InvalidValueError: at index 0: not a LatLng or LatLngLiteral with finite coordinates: not an Object

Any idea how can I convert that string of coordinates to the recognized format by Google such as LatLng or LatLngLiteral ?

CodePudding user response:

You can convert your coordinates to LatLng[] coordinates like this:

const polygon_coords = `(55.46701996570562, 11.983202375732418),
  (55.46604683879285, 11.982086576782223),
  (55.465316977846335, 11.983803190551754),
  (55.465900867684354, 11.985863127075191)`

  // Surround with [] to make an outer array.
  // and replace ( and ) with [ and ] to make inner arrays
  const jsonArray = `[
    ${polygon_coords.replace(/\)/g, ']')
                    .replace(/\(/g, '[')}
  ]`
  console.log(`Your json array: \n${jsonArray}\n`)

  const parsedCoords = JSON.parse(jsonArray)
  console.log(`${parsedCoords}\n`)

  // Assuming your coords are (lat,lng) order
  const latLngs = parsedCoords.map(pair => ({lat: pair[0], lng: pair[1]}))

  console.log(latLngs)
  const coords = new google.maps.Polygon({
    paths: latLngs,
    strokeColor: "#FF0000",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#FF0000",
    fillOpacity: 0.35,
    editable: true
  });

CodePudding user response:

  1. parse the polygon_coords string into its individual coordinates, use them to create either google.maps.LatLngLiteralgoogle.maps. or google.maps.LatLng` objects
var polygon_coords_str = '(55.46701996570562, 11.983202375732418),(55.46604683879285, 11.982086576782223),(55.465316977846335, 11.983803190551754),(55.465900867684354, 11.985863127075191)';
  polygon_coords_str = polygon_coords_str.substring(1, polygon_coords_str.length - 1);
  polygon_coords_str = polygon_coords_str.split("),(");
  var polygon_coords = [];
  for (var i = 0; i < polygon_coords_str.length; i  ) {
    polygon_coords.push({ // create a google.maps.LatLngLiteral
      // assume original data is (lat, lng)
      lat: parseFloat(polygon_coords_str[i].split(',')[0]),
      lng: parseFloat(polygon_coords_str[i].split(',')[1])
    })
  }
  1. use those to create the polygon:
  const coords = new google.maps.Polygon({
    paths: polygon_coords,
    strokeColor: "#FF0000",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#FF0000",
    fillOpacity: 0.35,
    editable: true
  });

screenshot of resulting polygon

code snippet:

// This example creates a simple polygon representing the Bermuda Triangle.
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 5,
    center: {
      lat: 55.4,
      lng: 11.9
    },
    mapTypeId: "terrain",
  });
  var polygon_coords_str = '(55.46701996570562, 11.983202375732418),(55.46604683879285, 11.982086576782223),(55.465316977846335, 11.983803190551754),(55.465900867684354, 11.985863127075191)';
  polygon_coords_str = polygon_coords_str.substring(1, polygon_coords_str.length - 1);
  polygon_coords_str = polygon_coords_str.split("),(");
  // console.log(polygon_coords_str);
  var polygon_coords = [];
  for (var i = 0; i < polygon_coords_str.length; i  ) {
    polygon_coords.push({
      lat: parseFloat(polygon_coords_str[i].split(',')[0]),
      lng: parseFloat(polygon_coords_str[i].split(',')[1])
    })
  }
  console.log("polygon_coords.length="   polygon_coords.length);
  for (var i = 0; i < polygon_coords.length; i  ) {
    console.log(polygon_coords[i]);
  }
  const coords = new google.maps.Polygon({
    paths: polygon_coords,
    strokeColor: "#FF0000",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#FF0000",
    fillOpacity: 0.35,
    editable: true
  });
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < coords.getPath().getLength(); i  )
    bounds.extend(coords.getPath().getAt(i));
  map.fitBounds(bounds);
  coords.setMap(map);
}
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>

<head>
  <title>Simple Polygon</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="map"></div>

  <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly&channel=2" async></script>
</body>

</html>

  • Related