Switch to next video from Youtube API (React)

I am attempting to have the next video in a channel play right after the other. Currently, the website has the videos showing one after the other, but my goal is to show one video and the second one plays right after the other is done. I have the function set up for the video ending, but right now it just causes an alert. I am using the Youtube Data API to pull in the videos and their information.

I am attempting to have the next video in a channel play right after the other. Currently, the website has the videos showing one after the other, but my goal is to show one video and the second one plays right after the other is done. I have the function set up for the video ending, but right now it just causes an alert. I am using the Youtube Data API to pull in the videos and their information.

Here is a snippet of the code I am using:

constructor() {
super();
this.state = {
  videos: [],
};

}

componentDidMount() {
fetch('https://www.googleapis.com/youtube/v3/search?key='APIKey'&channelId=UCXIJgqnII2ZOINSWNOGFThA&part=snippet,id&order=date&maxResults=2')
.then(results => {
return results.json();
}).then(data => {
let videos = data.items.map((videos) => {
return(
<div key={videos.items}>
<YouTube
className="player"
id="video"
videoId={videos.id.videoId}
opts={VIDEO_OPTS}
onEnd={this.playNextVideo}
/>
<h2>{videos.snippet.title}</h2>
<p className="channel">Video by: {videos.snippet.channelTitle}</p>
</div>
);
});
this.setState({videos: videos});
console.log("state", this.state.videos);
})

}

playNextVideo = () => {
alert('The video is done!');
}


Designing API Methods in JavaScript

Designing API Methods in JavaScript

Designing API methods in JavaScript is a very useful skill to learn and allows you to look at programming in a different perspective...

Originally published by Christopher T  at jsmanifest.com

A perspective whereas instead of building a project for your users, you're building a project for developers to use. And if you haven't built a library or an SDK before, this article may help you gain an understanding of where and how to start beginning with method design.

JavaScript is a loosely typed language which we as developers can take advantage of to create robust, multi-use APIs.

This article will go over a couple of rules to keep in mind when designing methods for an API in JavaScript.

1. Named Parameters

The first one we are going to talk about is named parameters. Back in the old days before ES6 was introduced, the only way to declare functions were function declarations using the function syntax. To determine where to go with execution flows, you would take a function arity (the number of arguments the function expects), convert it to an array and apply the rest of the logic depending on how the arguments look like.

In this example, the animaloptions, and callback are the parameters to the function and the arity will be three. The function is designed to create a new account, and each account will have some default settings if it wasn't provided by the caller:

function createAccount(
  username = '',
  password = '',
  nickname = '',
  email = '',
  gender = 'Male',
  bio = '',
  subscription = 'Basic',
  callback,
) {
  if (!username || !password || !email) {
    throw new Error(
      'You are missing one or all of the following fields: "username", "password", "email"',
    )
  }
  return api
    .createAccount({
      username,
      password,
      nickname,
      email,
      gender,
      bio,
      subscription,
    })
    .then((result) => {
      if (callback) callback(null, result)
    })
    .catch((error) => {
      console.error(error)
      if (callback) callback(error)
    })
}

createAccount(
'lucas',
'applebee123x123',
'',
'[email protected]',
'',
'My bio',
'Basic',
function cb(err, data) {
if (err) {
console.error(err)
}
// do something with data
},
)

The problem with this is that the caller has to know the exact order of arguments to pass in as the parameters to the function in order to function properly even if one or more parameters weren't required. It can be difficult to memorize the requirements in order while it can be very easy to mess up the order if you aren't careful. In addition, it doesn't really make much sense to make a parameter required if it isn't required to make the function do its work properly.

It will also be difficult to maintain in the future because when you or your boss needs to get rid of username and make it email as the new username instead, you would have to change the logic around.

A better practice is to simply use an object:

function createAccount({
username = '',
password = '',
nickname = '',
email = '',
gender = 'Male',
bio = '',
subscription = 'Basic',
callback,
}) {
if (!username || !password || !email) {
throw new Error(
'You are missing one or all of the following fields: "username", "password", "email"',
)
}
return api
.createAccount({
username,
password,
nickname,
email,
gender,
bio,
subscription,
})
.then((result) => {
if (callback) callback(null, result)
})
.catch((error) => {
console.error(error)
if (callback) callback(error)
})
}

We benefit from readability as well as more control over maintainability as you only need to remove the username from the code:

function createAccount({
password = '',
nickname = '',
email = '',
gender = 'Male',
bio = '',
subscription = 'Basic',
callback,
}) {
if (!password || !email) {
throw new Error(
'You are missing one or all of the following fields: "email", "password"',
)
}
return api
.createAccount({
password,
nickname,
email,
gender,
bio,
subscription,
})
.then((result) => {
if (callback) callback(null, result)
})
.catch((error) => {
console.error(error)
if (callback) callback(error)
})
}

Making the call also becomes more terse and readable:

createAccount({
password: 'applebee123x123',
email: '[email protected]',
bio: 'My bio',
callback: function cb(err, data) {
if (err) {
console.error(err)
}
// do something with data
},
})
2. Method Chaining / Fluent API

My favorite way of writing APIs is using the fluent API by method chaining.

Method chaining is simply the process of chaining multiple calls one after the other. The general idea is to achieve a readable and fluent code, thus making it quicker to understand. These methods are commonly verbs (like rotate)

For example:

getPhoto('../nemo_the_fish.jpg')
.applyFilter('grayscale', '100%')
.rotate(100)
.scale(1.5)

This translates to: "retrieve the image nemothefish.jpg and apply the grayscale filter with a value of 100%, rotate the image by 100 degrees and increase the scale by 1.5 times more."

A good thing about this practice is that it's very quick to get started with writing your own fluent API interface. You would simply return the reference to the context inside your method calls so that it can be chained:

const createWarrior = function createWarrior(name) {
let hp = 100
let battleCryInterval = 0

return {
bash: function(target) {
target -= 10
return this
},
// Increase the wrarior's health by 60, decrementing it by 1 every second for 60 seconds
battleCry: function battleCry() {
hp += 60
battleCryInterval = setInterval(() => {
hp -= 1
}, 1000)
setTimeout(() => {
if (battleCryInterval) {
clearInterval(battleCryInterval)
}
}, 60000)
return this
},
getHp: function getHp() {
return hp
},
}
}

const warrior = createWarrior('chris')
const otherWarrior = createWarrior('bob')

warrior
.battleCry()
.bash(otherWarrior)
.bash(otherWarrior)
.bash(otherWarrior)
.bash(otherWarrior)
.bash(otherWarrior)

const otherWarriorsHp = otherWarrior.getHp()

console.log(otherWarriorsHp) // result: 100

One of the greatest examples of a fluent API is jQuery, and thanks to the library's fluency it arguably makes it one of the easiest JavaScript libraries to both learn and use:

$(window).resize(function() {
$('#logbox').append('<div>The window resized</div>')
})

However, the method chaining fluent API comes with a few drawbacks.

The biggest drawback is that it can be difficult to set a breakpoint in the middle of a chain, making errors difficult to debug. In addition, it encourages too much procedural code. There are ways to get around the debugging issue though by inserting loggers at any step in the chain and using them to call subsequent methods with it.

Another drawback is that you can get caught up in the act of writing long sentences with tight dot notation access. This can get in the way of keeping things simple, so remember to keep things simple.

3. Function Polymorphism

You might have heard of the term polymorphism in other languages, generally where something behaves differently based on the context.

The same concept applies in function polymorphism in JavaScript. These are functions that behave accordingly to the arguments passed in (which is our context).

APIs often gather arguments to an array or array-like structure in order to have more control over them. Having them into an array structure allows them to do things like pass them into other functions in the same scope and vice versa.

Before arrow functions were introduced, the common practice to gather arguments inside polymorphic functions was using the array-like arguments object. Sometimes you might be in situations where you need to do more things with the arguments after you assigned them to an array. Even though arguments is an array-like object, it doesn't really function like a real array because it is missing essential array functions--and this is very limiting.

The way developers get around that is to make a separate, shallow copy by using Array.prototype.slice.call(). This is called method delegation. In order words, you delegate the slice() call to the Array.prototype object.

An example of this would look like this:

const args = Array.prototype.slice.call(arguments, 0)


This will copy the items starting at index 0 and return everything onwards.

Arguments doesn't have real methods like .push or .shift, so we convert it to an array with Array.prototype.slice so that we can get access to all of the array methods.

In ES6, we can easily convert it to an array by using the spread operator as shown below:

const someFunction = function(...args) {
console.log(args)
console.log(args.shift())
}

someFunction(1, 'hello', 'bob')
// result:
// [1, "hello", "bob"]
// 1

When you have your arguments into an array or array-like structure, you can determine where to go with the execution logic based on how the arguments look like. This makes it very flexible to be used for multiple purposes without writing too much code.

Without spreading:

const applyFilter = function(filter, value, options) => {
const args = [].slice.call(arguments, 0)
console.log(args.length) // result: 2
}

applyFilter('grayscale', '100%')

With spreading:

const applyFilter = (...args) => {
console.log(args.length) // result: 1
}

applyFilter('grayscale', '100%')

With this in mind, we can now determine how to handle the execution from these arguments:

const applyFilterToImage = (image) => {
return function applyFilter(...args) => {
// we can also grab args with [].prototype.slice.call(arguments, 0)

let options
let filters = {}
let callback

const arg1 = args[0]
// The caller wants to apply multiple filters
if (args.length === 1) {
  if (arg1 &amp;&amp; typeof arg1 === 'object') {
    filters = { ...arg1 }
    // Find out of the caller wants the new image with applied filters back by checking if a callback was passed in
    const arg2 = args[1]
    if (arg2 &amp;&amp; typeof arg2 === 'function') {
      callback = arg2
    }
  } else {
    throw new Error(
      'You must supply an object if you are only providing the first argument',
    )
  }
} else {
  if (args.length &gt; 2) {
    // The caller passed in options as the third argument
    if (typeof args[3] === 'object') {
      options = args[3]
    }
      // The caller provided a callback function and wants the image with applied filters passed back
    else if (typeof args[3] === 'function') {
      callback = args[3]
    }
  }
  // The caller wants to apply one filter
  if (typeof arg1 === 'string') {
    const filter = arg1
    const value = args[1]
    filters[filter] = value // or filters = { [filter]: value }
  } else {
    if (callback) {
      callback(new Error('Filter is not a string'))
    }
  }
}
  const newImg = api.filterImage(filters, options)
  if (callback) {
    return callback(null, newImg)
  }

}
}

const img = '../bob_the_builder.jpg'
const applyFilter = applyFilterToImage(img)
const callback = (newImg) => {
console.log(newImg)
}

applyFilter({
grayscale: '100%',
rotate: 100,
scale: 1.5,
}, callback)

The simple function allows the developer to use it in multiple ways:

  1. Apply a single filter by providing a string and a value as the first and second argument.
  2. Or apply multiple filters by providing an object of key/value pairs as the first argument.
  3. Or apply a single filter by providing an object of one filter key/value as the first argument.
  4. Optionally receive the newly filtered image back through a callback as the second or third argument (position depends on what they passed in for the filters.)
Conclusion

That concludes the end of this article. Look out for more posts from me in the future!

Originally published by Christopher T  at jsmanifest.com

===========================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Svelte.js - The Complete Guide

☞ The Complete JavaScript Course 2019: Build Real Projects!

☞ Become a JavaScript developer - Learn (React, Node,Angular)

☞ JavaScript: Understanding the Weird Parts

☞ JavaScript: Coding Challenges Bootcamp - 2019

☞ The Complete Node.js Developer Course (3rd Edition)

☞ Angular & NodeJS - The MEAN Stack Guide

☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

☞ Node.js Absolute Beginners Guide - Learn Node From Scratch

Introduction to JavaScript Payment Request API

Introduction to JavaScript Payment Request API

Quick introduction to JavaScript Payment Request API. It provides a browser-based method to collect customer payment and contact information that can be sent to the backend server to process the payment. The aim is to reduce the number of steps involved in completing an online payment.

The Payment Request API is a new JavaScript API that provides a cross-browser standard to collect the payment, address, and contact information from a customer that can be used to process an order. It also facilitates the exchange of this information between the browser and the website. The whole idea behind this is to improve the user online shopping experience by making it easy for the user to store payment and contact information in the browser.

API Usage

The Payment Request API is still in active development and is only supported by the last few versions of modern browsers. Before we start making a payment request, we should feature detect to ensure that the API is supported by the browser:

if(window.PaymentRequest) {
    // Yes, we can use the API
} else {
    // No, fallback to checkout page
    window.location.href = '/checkout';
}

Note: You can only use the Payment Request API on sites that are served over https.

PaymentRequest Object

A payment request is always started by creating a new object of PaymentRequest - using the PaymentRequest() constructor. The constructor takes two mandatory parameters and one optional parameter:

  • paymentMethods defines which forms of payment are accepted. For example, you may only accept Visa and MasterCard credit cards.
  • paymentDetails contains the total payment amount due, taxes, shipping cost, display items, etc.
  • options is an optional argument that can be used to request additional details from the user, such as name, email, phone, etc.

Let's create a new payment request with only required parameters:

const paymentMethods = [
    {
        supportedMethods: ['basic-card']
    }
];

const paymentDetails = {
    total: {
        label: 'Total Amount',
        amount: {
            currency: 'USD',
            value: 8.49
        }
    }
};

const paymentRequest = new PaymentRequest(
    paymentMethods,
    paymentDetails
);

Notice the supportedMethods parameter in paymentMethods object. When it is set to basic-card, both debit and credit cards of all networks will be accepted. However, we can limit the supported networks and types of the card. For example, with the following only Visa, MasterCard and Discover credit cards are accepted:

const paymentMethods = [
    {
        supportedMethods: ['basic-card'],
        data: {
            supportedNetworks: ['visa', 'mastercard', 'discover'],
            supportedTypes: ['credit']
        }
    }
];
// ...

Payment Details

The second mandatory parameter that is passed to PaymentRequest constructor is the payment details object. It contains the total of the order and an optional array of display items. The total parameter must contain a label parameter and an amount parameter with currency and value.

You can also add additional display items to provide a high level breakdown of the total:

const paymentDetails = {
    total: {
        label: 'Total Amount',
        amount: {
            currency: 'USD',
            value: 8.49
        }
    },
    displayItems: [
        {
            label: '15% Discount',
            amount: {
                currency: 'USD',
                value: -1.49
            }
        },
        {
            label: 'Tax',
            amount: {
                currency: 'USD',
                value: 0.79
            }
        }
    ]
};

The displayItems parameter is not meant to display a long list of items. Since space is limited for the browser's payment UI on mobile devices, you should use this to display only top-level fields such as subtotal, discount, tax, and shipping cost, etc.

The PaymentRequest API does not perform any calculations. So it is your web application that is responsible for providing the pre-calculated total amount.

Requesting Additional Details

The third optional parameter can be used to request additional information from the user such as name, email address, and phone number:

// ...
const options = {
    requestPayerName: true,
    requestPayerPhone: true,
    requestPayerEmail: true,
};

const paymentRequest = new PaymentRequest(
    paymentMethods,
    paymentDetails,
    options
);

By default, all of these values are false, but adding any of them to options object with a value true will result in an extra step in the payment UI. If the user has already stored these details in the browser, they will be pre-populated.

Display Payment UI

After creating a PaymentRequest object, you must call the show() method to display the payment request UI to the user. The show() method returns a promise that resolves with a PaymentResponse object if the user has successfully filled in the details. If there is an error or the user closes the UI, the promise rejects.

// ...
const paymentRequest = new PaymentRequest(
    paymentMethods,
    paymentDetails,
    options
);

paymentRequest
    .show()
    .then(paymentResponse => {
        // close the payment UI
        paymentResponse.complete()
            .then(() => {
                // TODO: call REST API to process the payment at backend server
                // with the data from `paymentResponse`.
            });
    })
    .catch(err => {
        // user closed the UI or the API threw an error
        console.log('Error:', err);
    });

With the above code, the browser will show the payment UI to the user. Once the user has filled in the details and clicked on the 'Pay' button, you will receive a PaymentResponse object in the show() promise. The payment request UI is closed immediately when you call the PaymentResponse.complete() method. This method returns a new promise so that you can call the backend server with the information collected and process the payment.

If you wanted to call the backend server to process the payment while the payment UI is showing a spinner, you can delay the call to complete(). Let us create a mock function for payment processing with the backend server. It takes paymentResponse as a parameter and returns a promise after 1.5 seconds that resolves to a JSON object:

const processPaymentWithServer = (paymentResponse) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve({ status: true });
        }, 1500);
    });
};
//...
paymentRequest
    .show()
    .then(paymentResponse => {
        processPaymentWithServer(paymentResponse)
            .then(data => {
                if (data.status) {
                    paymentResponse.complete('success');
                } else {
                    paymentResponse.complete('fail');
                }
            });
    })
    .catch(err => {
        console.log('Error:', err);
    });

In the example above, the browser payment UI will show a processing screen until the promise returned by processPaymentWithServer() method is settled. We also used 'success' and 'fail' strings to tell the browser about the outcome of the transaction. The browser will show an error message to the user if you call complete('fail').

Payment Request Abort

If you want to cancel the payment request due to no activity or any other reason, you can use the PaymentRequest.abort() method. It closes the payment request UI immediately and rejects the show() promise.

// ...
setTimeout(() => {
    paymentRequest.abort()
        .then(() => {
            // aborted payment request
            console.log('Payment request aborted due to no activity.');
        })
        .catch(err => {
            // error while aborting
            console.log('abort() Error: ', err);
        });
}, 5000);

If you want to learn more about the Payment Request API, here is a good resource that discusses the main concepts and usage of the API.

Map Custom Marker and Controls | JavaScript, CSS and API

Map Custom Marker and Controls | JavaScript, CSS and API

How we can add a custom marker on google map using JavaScript & CSS? Solution: JavaScript Google Map Marker With CSS, Custom API Map Controls.

Maybe you have seen custom markers on the map on some tour & travels websites. They show their all destination using those markers on the map. There are many online websites or services for creating custom markers, but we can also create those own using google map’s API. Google provides many kinds of API for developers on its Cloud Platform.

Today you will learn to add a custom marker on the map with your choosing place. This possible because of API, I am using jQuery & jQuery-Migrate for this program. As you know jQuery is a JavaScript library that’s why I am calling this a JavaScript Custom Map Marker Program. Suppose you have an online hotel booking site & you want to show all the places where your hotel is, then this will very useful for you.

So, Today I am sharing JavaScript Google Map Marker With CSSA Custom API Map Controls With JS & CSS. This program marker will place on given longitude & latitude. Its also has zoom in, zoom out, center, & full-screen buttons. There also is an option bar to choosing road view or satellite view. If you want to change the marker to other places, then you have just change the longitude & latitude.

If you are thinking now how this custom map marker actually is, then see the preview given below.

Preview Of Custom API Map Control

See this video preview to getting an idea of how this custom map with marker looks like.


Now you can see this visually. If you like this then get the source code of its.

Discussion

Before sharing source code, let’s talk about this. As you know I have used API, that runs the whole map’s function. I have used an image for the marker’s icon, after that placed on the chosen address in map. For placing the marker I have created some variables for the functions like whole map, long, lat, icon, etc.

All the functions like zoom, focus center, choosing satellite or road view are done by google’s provided API commands. There is another function is when you will click on the marker then the address will open in a new tab. You can remove this feature by removing the code in JS file, I have left a comment on every function’s code section. You can easily identify the codes are for your decided part.

In the CSS section, I have placed all the things you can see on the preview. Works like managing colors, positioning, etc are handled by CSS. As you can see all the buttons in the map are created using Font-Awesome icons. If you have good knowledge of HTML, CSS & JavaScript then you can understand the codes easily. These codes are looking tough but believe me that all are default functions of the API, I have just called on the right place.

For using it on your websites or project you just have to change the longitude & latitude on the JS file. If you get any trouble you can ask me on the comment section or direct message on the Facebook page.

JavaScript Google Map Marker With CSS Source Code

For creating this program you have create 3 files. First for HTML, second for CSS, & third for JavaScript. Follow the steps to creating this without any error.

index.html

Create an HTML file named ‘index.html‘ and put these codes given below.

<!DOCTYPE html>
<!-- code by webdevtrick ( https://webdevtrick.com )-->
<html lang="en" >
 
<head>
  <meta charset="UTF-8">
  <title>CSS Custom Marker On Map | Webdevtrick.com</title>
  
  <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'>
      <link rel="stylesheet" href="style.css">
</head>
 
<body>
 
  <div class="full-screen">
  <div id="map" class="map"></div>
 
    <!--controls-->
    <span id="zoomIn" class="btn zoom in">
        <i class="fa fa-plus"></i>
    </span>
    <span id="zoomOut" class="btn zoom out">
        <i class="fa fa-minus"></i>
    </span>
 
    <span id="center" class="btn zoom center">
        <i class="fa fa-crosshairs"></i>
    </span>
 
    <div class="mapTypeId">
        <select id="mapTypeId">
            <option value="1">Roadmap</option>
            <option value="2">Satellite</option>
        </select>
    </div>
 
</div>
  <script src='https://maps.googleapis.com/maps/api/js?key=AIzaSyCLFomDOPKqvvITt7tv_hZG0PDlWB2-q0g'></script>
<script src='https://code.jquery.com/jquery-1.11.3.min.js'></script>
<script src='https://code.jquery.com/jquery-migrate-1.2.1.min.js'></script>
 
    <script  src="function.js"></script>
 
</body>
</html>

style.css

Now create a CSS file named ‘style.css‘ and put these codes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

/** code by webdevtrick ( https://webdevtrick.com ) **/
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}
.full-screen {
  position: relative;
  width: 100%;
  height: 100%;
}
.full-screen .map {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
.full-screen .btn {
  cursor: pointer;
  border: 0;
  border-radius: 2px;
  background-color: white;
  box-shadow: 1px 1px 3px 0 rgba(0, 0, 0, 0.1);
  transition: all 300ms ease-in-out;
}
.full-screen .btn.zoom {
  position: absolute;
  right: 20px;
  color: #e60023;
  font-size: 20px;
  padding: 5px 8px;
}
.full-screen .btn.zoom.in {
  top: 50%;
  margin-top: -37px;
}
.full-screen .btn.zoom.out {
  bottom: 50%;
  margin-bottom: -37px;
}
.full-screen .btn.zoom.center {
  top: 50%;
  margin-top: -87px;
}
.full-screen .btn.zoom:hover,
.full-screen .btn.zoom:active {
  color: white;
  background-color: #e60023;
}
.full-screen .btn.zoom:active {
  opacity: 0.75;
}
.full-screen .mapTypeId {
  position: absolute;
  top: 20px;
  left: 5px;
  border-radius: 2px;
  background-color: #e60023;
  box-shadow: 1px 1px 3px 0 rgba(0, 0, 0, 0.1);
  width: 90px;
  overflow: hidden;
  color: white;
  padding: 8px 0;
}
.full-screen .mapTypeId select {
  color: white;
  text-indent: 10px;
  text-transform: uppercase;
  font-weight: 700;
  width: 100%;
  position: relative;
  top: -2px;
  border: none;
  box-shadow: none;
  background-color: #e60023;
  background-image: none;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
}
.full-screen .mapTypeId select:focus {
  outline: none;
}

function.js

The final step, Create a JavaScript file named ‘function.js‘ and put the codes.

/**code by webdevtrick ( https://webdevtrick.com ) **/
$(document).ready(function() {

var map;
var marker;
var lat = 28.7407056;
var lng = 77.0577493;
var ico = new google.maps.MarkerImage("https://webdevtrick.com/wp-content/uploads/location.png");

var overlay = new google.maps.OverlayView();
overlay.draw = function() {};	

function initialize () {
	var mapCanvas = document.getElementById('map');
	var mapOptions = {
	zoom: 13,
	center: {
	lat: lat, 

     lng: lng
},
mapTypeControl: false,
zoomControl: false,
panControl: false,
        scaleControl: false,
        streetViewControl: false,
        scrollwheel: false
}
 
map = new google.maps.Map( mapCanvas, mapOptions );
 
overlay.setMap(map);
   ZoomControl(map);
   addMarker(map);
  
}
 
// Marker
function addMarker ( map ) {
marker = new google.maps.Marker({
            map: map,
            draggable: false,
            icon: ico,
            position: new google.maps.LatLng( lat, lng )
        });
 
        mouseOverHandler = function () {
         showMarker(marker);
        }
        mouseClickHandler = function () {
         clickMarker(lat, lng);
        }
 
        google.maps.event.addListener( marker, 'click', mouseClickHandler );
        google.maps.event.addListener( marker, 'mouseover', mouseOverHandler );
}
 
// Marker Click
function clickMarker ( lat, lng ) {
var url = 'https://maps.google.com/maps?q='+lat+','+lng+'&z=18';
window.open(url, '_blank');
}
 
// Zoom
function ZoomControl ( map ) {
var zoomIn = document.getElementById('zoomIn');
var zoomOut = document.getElementById('zoomOut');
 
google.maps.event.addDomListener(zoomOut, 'click', function() {
var currentZoomLevel = map.getZoom();
if(currentZoomLevel != 0){
map.setZoom(currentZoomLevel - 1);}    
});
 
google.maps.event.addDomListener(zoomIn, 'click', function() {
var currentZoomLevel = map.getZoom();
if(currentZoomLevel != 21){
map.setZoom(currentZoomLevel + 1);}
});
}
 
// MapTypeId
function TypeIdChange ( option ) {
switch (option) {
            case "1":
                map.setMapTypeId( google.maps.MapTypeId.ROADMAP );
                break;
               case "2":
               map.setMapTypeId( google.maps.MapTypeId.SATELLITE );
                break;
            default:
                map.setMapTypeId( google.maps.MapTypeId.ROADMAP );
        }
}
// center
$( '#center' ).on( 'click', function () {
map.setZoom( 13 );
map.setCenter(new google.maps.LatLng( lat, lng ) );
map.setMapTypeId( google.maps.MapTypeId.ROADMAP );
$( '#mapTypeId' ).val( "1" ).trigger('click');
});
 
// center
$( '#center' ).on( 'click', function () {
map.setZoom( 13 );
map.setCenter(new google.maps.LatLng( lat, lng ) );
map.setMapTypeId( google.maps.MapTypeId.ROADMAP );
$( '#mapTypeId' ).val( "1" ).trigger('click');
});
 
$( '#mapTypeId' ).change( function () {
var self = $(this);
TypeIdChange( self.val() );
});
 
google.maps.event.addDomListener( window, 'load', initialize );

That’s It. Now you have successfully created JavaScript Google Map Marker With CSS. In other words, A Custom API Based Map Controls Like add Marker, Zoom In & Out, etc.

Thanks For Visiting, Keep Visiting.

Originally published on https://webdevtrick.com