How to add Multiple Google Maps Markers using Google Map API JS V3

In today’s tutorial, we are going to show you how you can add multiple markers to a single Google Map. Not just that though, we are also going to show you how to add custom map styles and custom markers to make your map look even better.

I’m just going to go ahead and show the full code we use to do this, then explain what everything does after. So let’s begin…

In our example, we are using the ID map so your HTML will simply look like this:


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

The only CSS styles we have added are:


#map {
    position: relative;
    width: 100%;
    height: 350px;
    display: block;
}

Pretty straight forward so far right? If you want a larger map then just increase the height of the #map in your CSS code.

For the Google Map to work, we need to get a Google API Key. If you need instructions on this then visit here.

You will need to include the JavaScript between the before the sript that runs your JS Google Map API code. This will be as follows:


  <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
  type="text/javascript"></script>

If you are using WordPress, then you can register and enqueue as follows:


    wp_register_script('google-js', 'https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyBYL8d1Bnuy1b0EwX9iOldIuORnSMSJcjE' );
    wp_enqueue_script('google-js');	

The WordPress code will go in either your theme or child-theme functions.php file if you have one set up.

Now for the JS code…

You will need to call the following code after you load the Google API script mentioned above:


/* Google Map - Contact Us */

if ($("#map").length > 0) {

    function initializeMap() {

        var locations = [
            ['Battersea Park Road', 51.4705666,-0.1728984, 2],
            ['Webbs Road', 51.4575458,-0.165245, 1]
        ];

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 14,
            center: new google.maps.LatLng(51.465691,-0.1706737),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        var infowindow = new google.maps.InfoWindow();

        var marker, i;

        var icon = {
            url: "/wp-content/themes/spectrum/assets/img/map-marker.png",
            scaledSize: new google.maps.Size(70, 70)
        }; 

        var marker = new google.maps.Marker({
            map: map,
            animation: google.maps.Animation.DROP,
            icon : icon
        });            

        for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                map: map,
                icon : icon
            });

            google.maps.event.addListener(marker, 'click', (function (marker, i) {
                return function () {
                    infowindow.setContent(locations[i][0]);
                    infowindow.open(map, marker);
                }
            })(marker, i));
        }

        var styles = [
            {"featureType":"water","elementType":"geometry","stylers":[{"color":"#e9e9e9"},{"lightness":17}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#ffffff"},{"lightness":17}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#ffffff"},{"lightness":29},{"weight":0.2}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":18}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":16}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":21}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#dedede"},{"lightness":21}]},{"elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#ffffff"},{"lightness":16}]},{"elementType":"labels.text.fill","stylers":[{"saturation":36},{"color":"#333333"},{"lightness":40}]},{"elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"geometry","stylers":[{"color":"#f2f2f2"},{"lightness":19}]},{"featureType":"administrative","elementType":"geometry.fill","stylers":[{"color":"#fefefe"},{"lightness":20}]},{"featureType":"administrative","elementType":"geometry.stroke","stylers":[{"color":"#fefefe"},{"lightness":17},{"weight":1.2}]}      
        ];
    
        map.setOptions({styles: styles});            
    
    }
    
    initializeMap();    

} 

So first things first... we added if ($("#map").length > 0) { so that it will only run the JS code on pages that call the map. If you allow it to run on any page, you will find yourself with some console errors, that's why we only run the code on pages that contain the map.

Secondly, we created an array of locations here; var locations = [, you can add as many as you like. Here, we include the info window title, the latitude and longitude coordinates which you can obtain from the URL when you click a location on Google Maps, and also the ID of the location, in our case there are only 2.

In our example, we added two markers, so what we did here is set the 'centre' point to a location that is in the centre of both of the locations so they show correctly on the map. The lat/long value for the centre can be defined here: center: new google.maps.LatLng(51.465691,-0.1706737),.

We then added a custom marker as were not a huge fan of the 'basic' google map markers. You will see on this line; url: "/wp-content/themes/spectrum/assets/img/map-marker.png", that we added the path to our custom marker. We also scaled the marker so that it is double the size so it looks awesome on retina ; ) This was defined on the next line here; scaledSize: new google.maps.Size(70, 70).

We then created a for loop which goes through all the locations and adds each of the pointers on the map using the custom icon that we created.

Finally, we decided to change the default styles of the map. It's always nice to customise this and make it unique. You will see we added var styles = [ and included a long line of code to adjust the map styles. Fear not though, this is very easy to do! Simply head to Snazzy Maps, pick a cool style the matches your website then replace the code with the one provided through their website.

What we end up with our example is a Google Map that looks as follows:

SWEET! We nailed it guys. We sure hope this helps you, if you need any assistance, feel free to drop us a comment below.

As always, happy coding!

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

10 Frontend Web Development Tools for 2020

Web development is constantly evolving, with so many libraries and frameworks available and appearing all the time and replacing other less efficient tools. As developers, we must always keep up-to-date with the latest trends and find out the best solutions for your digital projects. Today, we will go through the best tools to use for Frontend Development in 2020.

1. Chrome Developer Tools

This is a set of tools that helps developers get easy access using the browser, which saves devs a lot of time. It makes things super easy by showing you errors in the code directly through the console. When it comes to styling, you get a real-time preview of the changes you make on the fly saving a lot of time. It’s super easy to use and it includes so many additional features. You can even audit your website through the console using PageSpeed Insights. If this is a new tool for you, just know it is perfect to ensure that your website is fully optimised for speed, giving recommendations on how you can make your site faster which in turn will improve your SEO.

The Google browser updates every 6 weeks, so you need to check its web portal to continue developing at an advanced level and to keep up-to-date with the new features. These tools allow you to perform a wide variety of tests in your browser, which helps you save a huge amount of time. Using ‘Device mode’ for example, you can work and test your site to ensure it’s responsive and works across several devices. The ‘sources panel’ allows JavaScript debugging with breakpoints which makes life a lot easier when it comes to debugging. ‘Timeline assists’ helps you find performance issues during running time. It’s essential to have a super-fast website and this tool is extremely helpful.

2. TypeScript

TypeScript is an open-source programming language. It is a strict syntactical superset of JavaScript and it adds optional static typing to the language. TypeScript can be used to develop JavaScript applications for both client-side and server-side execution just like Node.JS or Deno.

TypeScript is designed for the development of large applications and transcompiles to JavaScript. As TypeScript is a superset of JavaScript, existing JavaScript programs are also valid TypeScript programs.

TypeScript creates a great web development environment for front-end developers.

TypeScript is a very modern front-end development tool that accepts many integrations. One of the key features is that it accepts other JS libraries, making it possible to use TypeScript on any environment running JavaScript. It accepts definition files that can contain type information of existing JavaScript libraries, such as C, C ++ header files and it is portable in browsers, devices and operating systems.

3. GitHub

GitHub is a Git repository hosting service and it includes many features. Git is a command-line tool that provides a Web-based graphical interface. It also provides access control and several collaboration features, such as wikis and basic task management tools for every project.

The key features of GitHub are allowing all the code in one place, coordinating use, staying aligned, and, after each GitHub project management tool, the developers can host the direct documentation through the repositories.

4. Sass / SCSS

Sass/SCSS is the most reliable and robust CSS extension language. This web development tool helps to extend the functionality of an existing CSS such as variables, inheritance, and nesting with ease. Sass is an open-source project that attracts updated CSS preprocessors. This tool gives you a hand in writing a code that can be easily maintained, thus reducing the amount of CSS you need to code.

Usually, with this, you have a ‘mixins’ file which contains code to simplify coding. As a brief example, let’s say you execute the following code to work cross-browser:


    -webkit-transition: all .3s linear;
    -moz-transition: all .3s linear;
    -o-transition: all .3s linear;
    transition: all .3s linear;

Well, the awesome thing with Sass/SCSS is that we can condense this to a single line of code as follows:-


    @include transition(all 0.3s linear);

It’s a massive time-saver!

Before you can use Sass/SCSS, it needs to be configured on your project. Sass allows you to nest your CSS sectors using a technique that follows the visual hierarchy of your HTML. There are also several applications that will help you use Sass for Mac, Linux and Windows platforms. Some of the key features are that it is simple and easy to use this front-end tool to write any code, it accepts language extensions such as variables, inheritance, and nesting, it has many useful functions for manipulating colours and other values and it has advanced functions such as library control directives.

To get started, I would recommend reading this post that will give you a starter template to use mixins and save a lot of time when it comes to writing CSS code.

5. jQuery

jQuery is one of the most popular JavaScript libraries that is widely used for front-end development. This large library allows developers to focus on the functionality of different aspects. Through this JavaScript library, development can become very easy, such as handling HTML documents, traversing and Ajax. The key features are that it facilitates the creation of highly interactive web applications, offers a powerful theme mechanism, is very friendly and stable, offers extensive support for the browser. On top of this, it’s free and it’s always updating.

In a nutshell, jQuery is very lightweight (write less, do more”) based on the JavaScript library. The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish and wraps them into methods that you can call with a single line of code. Simplicity and giving devs the ability to code faster is always a bonus!

6. Sublime Text

Sublime Text is a sophisticated text editor which is widely used among developers. It includes wide features such as Syntax Highlighting, Auto Indentation, File Type Recognition, a wicked sidebar, Macros, Plug-in and Packages that make it easy for working with codebase.

The key features of Sublime Text are that it is compatible with many programming languages, offers Python-based plugin API and it has simultaneous editing which allows for the same interactive changes across multiple domains. We 100% recommend you checking this out, once we started using it, we never looked back!

7. CodePen

CodePen is a web development environment for front-end designers and developers. It enables faster and smoother development. It allows you to add HTML, CSS and JS code to create test cases before implementing it on websites. Another cool feature is that it has a massive library of functions that could be applicable to your site. What does this mean? Well, it’s going to save you a lot of time coding something from scratch when an already implemented code may just need a few edits to make it applicable to your website.

The key features are that it includes great features for faster CSS writing, allows live viewing and live synchronisation and the API prefill feature allows you to add links and demo pages, without having to code anything. A similar website we tend to use is JSFiddle, which offers all the same features. However, the preference is dependant on each user.

8. AngularJS

AngularJS is a structural framework for dynamic web applications. It lets you use HTML as your template language and lets you extend HTML’s syntax to express your application components clearly and succinctly. Its data binding and dependency injection eliminate much of the code you currently have to write. It is an open-source web application framework that allows you to simplify the front-end development process by creating an expressive environment that is legible and accessible. Some of its key advantages are that it is free, it’s open-source and widely used by thousands of developers, allowing you to create RICH Internet Applications, it automatically manages the appropriate JavaScript code for each browser and offers the option to write the application from the client using JavaScript and MVC. AngularJS is quite commonly used today so it’s an important framework to learn moving forward. There have been many times where we have had to take over websites that utilise AngularJS, so stay ahead of the game and learn something new, this is definitely worthwhile!

9. Grunt

Grunt is one of the best front-end development tools when it comes to automating tasks. It is quite commonly used with NodeJs, which offers plugins for common tasks and is very flexible and widely adopted. It offers an alternative to writing down all kinds of tasks that go well with your requirements.

The key features of Grunt are allowing automation of repetitive tasks without a great deal of effort, creating the workflow simply by writing a configuration file, including activities for extending the functionality of plugins/scripts, it speeds up the development process, it also increases the performance of your projects and reduces the chance of errors while you are performing repetitive tasks.

10. Npm

Another great tool is Npm which represents the Node package manager for JavaScript. With Npm, you are able to discover reusable code packages and assemble them in powerful and new ways. It is a command-line utility used for interacting with a named repository that helps in a package.

Some of its key features include the ability to publish and control access to a namespace, you can reuse and discover a massive library of free code packages in the registry, manage public and private code using the same workflow and find out where you have reused code within your teams.

Conclusion

So why is it so important to keep up to date with the latest technologies? Well, as we already mentioned, the world wide web is always evolving and new tools are always being created to make it easier for developers to code. Quite a lot of these tools mentioned help developers by enabling them to create the same functionalities a lot quicker; delivering a project in a shorter time frame is highly cost-effective and it saves you the time you can use for other tasks. In addition to this, you may have to take over a project that uses a framework that you are not familiar with. That being said, it’s always best to keep up-to-date with the latest technologies to prepare you to complete any given task which in turn will allow you to complete more jobs more quickly and effectively.

Well, we sure hope you loved this post, leave us a comment and let us know your thoughts. If we missed anything you might think that should be in this post, let us know in the comments!

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

How to show a preview image of an input file upload

Today we’re going to show you how to show a preview image of a file that you upload using the HTML input type file.

Okay, let’s dig right into it, firstly, let’s image you have the following HTML markup:-


<input type="file" onchange="readURL(this);" />
<img id="blah" alt="Your Image Preview" />

We’re going to add a bit of CSS styling to hide the image initially and only display the image once the file has been uploaded.


img {
  max-width: 180px;
  display: none;
}

input[type=file] {
  padding: 10px;
  background: #2d2d2d;
  color: #FFF;
  display: block;
  margin-bottom: 20px;
}

Now, we just need the jQuery function to show the preview and add the uploaded file to replace the image, you can do this as follows:


function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('#blah')
        .attr('src', e.target.result);
      $('#blah').show();
    };

    reader.readAsDataURL(input.files[0]);
  }
}

The end result will look something as follows:-

If you take a look at this blog post, you will see how you can take this one step further to make it even more visually appealing 😉

This is a pretty cool feature to add to file uploads to make them a bit more visually impressive to the user.

You can check out and test the CodePen we created here.

As always, we hope you have found this useful… make sure to leave a comment and stay tuned for the next tutorial!

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

We’re Hiring! 1 x Freelance Web Developer

We are currently in need of a website developer to work with to complete ad-hoc jobs as required as we quite often we tend to get a work overload that we could do with some assistance in order to complete tasks in a timely manner. We always aim to deliver any type of project in a timely manner which is how we maintain long-term relationships with our clients.

Please only submit your application if you are competent in the following:-

  • Bespoke WordPress Theme Builds
  • Plugin Customisation
  • HTML5 / CSS3 / PHP / jQuery / JavaScript / SASS / SCSS
  • Bootstrap 4
  • Providing estimates and delivering on time
  • Developing Email Templates using MailChimp
  • Based in Europe*

 

Optional requirements but not essential:-

  • Magento
  • Shopify
  • Laravel
  • Various other frameworks as there tends to be a varied type of work.

 

Please submit your hourly rate and a list of your expertise within your application.

To get started, email your CV and Cover Letter to [email protected]

Thank you for reading, and we look forward to hearing from you!

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

How to build a custom Countdown Timer in JavaScript [coming soon page]

Have you ever seen the countdown timers to a specific date on a ‘Website Coming Soon’ page or a countdown to an upcoming event? You know the ones that update every second until it reaches the ‘deadline’. Well in this tutorial we are going to show you how to do this.

You can see a working version here on JSFIDDLE.

So here we go:

HTML


<h1>Countdown Clock</h1>
<div id="clockdiv">
  <div>
    <span class="days"></span>
    <div class="smalltext">Days</div>
  </div>
  <div>
    <span class="hours"></span>
    <div class="smalltext">Hours</div>
  </div>
  <div>
    <span class="minutes"></span>
    <div class="smalltext">Minutes</div>
  </div>
  <div>
    <span class="seconds"></span>
    <div class="smalltext">Seconds</div>
  </div>
</div>

CSS


body {
  text-align: center;
  background: #169fe6;
  font-family: sans-serif;
  font-weight: 100;
}

h1 {
  color: #FFFFFF;
  font-weight: 100;
  font-size: 40px;
  margin: 40px 0px 20px;
}

#clockdiv {
  font-family: sans-serif;
  color: #FFFFFF;
  display: inline-block;
  font-weight: 100;
  text-align: center;
  font-size: 30px;
}

#clockdiv > div {
  padding: 10px;
  border-radius: 3px;
  background: #3f72a3;
  display: inline-block;
}

#clockdiv div > span {
  padding: 15px;
  border-radius: 3px;
  background: #FFFFFF;
  display: inline-block;
}

.smalltext {
  padding-top: 5px;
  font-size: 16px;
}

#clockdiv span {
   color: #1a1a1a;
}

JavaScript


function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = new Date('12/25/2016');
initializeClock('clockdiv', deadline);

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

CSS/jQuery – How to add a custom Back to top Icon

The Back to top link allows users to smoothly scroll back to the top of the page. It’s a little detail that enhances the navigation experience on a website with long pages.

How to add a custom back (scroll) top top icon?

Firstly, within your footer, add the following HTML:-


<a href="#" class="back-to-top"></a>

Then add the following CSS:-


.back-to-top {
    display: none;
    background-image: url(../img/back-to-top.png); // Link this to your image
    background-repeat: no-repeat;
    position: fixed;
    height: 30px; // The height of the icon you added for the background
    width: 30px; // The width of the icon you added for the background
    background-size: 30px; // The height and width of the background image
    bottom: 30px;
    height: 30px;
    z-index: 999;
}

The magic behind it is adding jQuery to handle the fade in/out when the scroll point is further down the page. Add the following jQuery code:-


/* Back to Top */

var offset = 220;
var duration = 500;
jQuery(window).scroll(function() {
	if (jQuery(this).scrollTop() > offset) {
		jQuery('.back-to-top').fadeIn(duration);
	} else {
		jQuery('.back-to-top').fadeOut(duration);
	}
});

jQuery('.back-to-top').click(function(event) {
	event.preventDefault();
	jQuery('html, body').animate({scrollTop: 0}, duration);
	return false;
});	

And there you have it, you now have an icon that appears on the bottom right-hand corner when you scroll down the page. Clicking this element will smoothly scroll back to the top of the page.

Remember to include the jQuery library and jQuery UI for this to work properly.

Any difficulties, just ask away in the comments!

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

jQuery – How to open a link in a new tab when a user presses CTRL + Click

If you are using jQuery for any reason to open a link, you may notice that if you will run into an issue if you have something along the lines of the code below:


window.location = '/demo';

Okay great, it opens the link but a client of mine reported that the link would not open when you use CTRL + Click or CMD + Click. The above code will not open a link in a new tab if you hold CTRL/CMD and click as a normal hyperlink would behave. Instead it will continue to open within the same page. To get around this, you can amend your code as below:-


jQuery('#foo').bind('click', function(e) {
   e.preventDefault(); 
   if (e.ctrlKey){
     window.open('/demo','_blank')
   }
   else {
     window.location = '/demo';
   }
});

Now, your link will now open in a new tab as you would find with standard HTML links. Happy days right?

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share