Categories
JavaScript Answers

How to add an InfoWindow to each marker with JavaScript Google Maps API v3?

To add an InfoWindow to each marker with JavaScript Google Maps API v3, we set the info property of the marker.

For instance, we write

const marker = new google.maps.Marker({
  map,
  position: point,
  clickable: true,
});

marker.info = new google.maps.InfoWindow({
  content: `<b>Speed:</b>: ${values.inst} knots`,
});

google.maps.event.addListener(marker, "click", () => {
  marker.info.open(map, marker);
});

to create a marker with the Marker constructor.

Then we set its info property to an InfoWindow instance which has the content set to some text.

And then we add a marker click listener with addListener to open the info window with marker.info.open when we click on the marker.

Categories
JavaScript Answers

How to check if a string is a float with JavaScript?

To check if a string is a float with JavaScript, we can use the isNaN function.

For instance, we write

if (!isNaN(value) && value.toString().includes(".")) {
  console.log("this is a float.");
}

to check if value is a number by negating the boolean returned by isNaN.

And then we check if a decimal point is included by converting value to a string with toString and call the includes method on the string.

If both are true, then value is a float.

Categories
JavaScript Answers

How to escape single quotes in JavaScript string for JavaScript evaluation?

To escape single quotes in JavaScript string for JavaScript evaluation, we use the string replace method.

For instance, we write

const escaped = searchKeyword.replace(/'/g, "\\'");

to call replace with the regex for single quotes and a string for the escaped single quotes to replace the single quotes in searchKeyword with the escaped version and return the escaped string.

Categories
JavaScript Answers

How to create and clone a JSON object with JavaScript?

To create and clone a JSON object with JavaScript, we can use the spread operator.

For instance, we write

const newJsonObj = { ...jsonObj };

to shallow copy the properties of the jsonObj object into a new object and assign the new object to newJsonObj.

Categories
JavaScript Answers

How to add a dotted stroke in the JavaScript canvas?

To add a dotted stroke in the JavaScript canvas, we call the setLineDash method.

For instance, we write

const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");

ctx.setLineDash([5, 10]);

ctx.beginPath();
ctx.lineWidth = "2";
ctx.strokeStyle = "green";
ctx.moveTo(0, 75);
ctx.lineTo(250, 75);
ctx.stroke();

to call setLineDash with the dash stroke lengths.

Then we call beginPath to start drawing.

We set the line width by setting lineWidth.

We set the stroke color by setting strokeStyle.

Then we draw by calling moveTo with the start point.

We call lineTo to draw to the end point.

And we call stroke to stop drawing.