Google maps directions - spaces between polylines

I am facing this ugly problem, can anyone solve this ? I want to get rid of that ugly spacec between lines. I need to keep the width.<a href="https://i.stack.imgur.com/zto4m.jpg" target="_blank"><img src="https://i.stack.imgur.com/zto4m.jpg"></a>

I am facing this ugly problem, can anyone solve this ? I want to get rid of that ugly spacec between lines. I need to keep the width.

code(adding polylines) :

thread {
        val response = getResponse(points[1].location, points[2].location, "driving21.").log()
        when (response) {
        is Result.Failure -&gt; "Fail".log()

        is Result.Success -&gt;
            response.value.routes[0].listOfLegs[0].listOfSteps.forEach { element -&gt;
                //                    element.points.log()
                val options = PolylineOptions()
                options.color(Color.rgb(255, 26, 140))
                options.width(50F)
                options.addAll(PolyUtil.decode(element.points))
                runOnUiThread {
                    map.addPolyline(options)
                }
            }
    }

EDIT:

after adding .jointType(JointType.ROUND)

there is another problem

React Apps with the Google Maps API and google-maps-react

React Apps with the Google Maps API and google-maps-react

This tutorial aims at integrating the google maps API to your React components and enabling you to display maps on your website.

This tutorial aims at integrating the google maps API to your React components and enabling you to display maps on your website.

Introduction to Google Maps API.

At some point of our lives, we’ve all gotten a chance to use and interact with the google maps, either through finding directions, viewing our current location, ordering cabs or estimating distance and time from one point to another.

Table of Contents

Including the Google maps API in a React App is actually far much easier than expected due to its rich documentation which I highly suggest that you look into, and the npm package by Fullstack React.

Prerequisite:

Go on ahead and grab your API key here.

  1. Simply click on the Get Started button
  2. Tick on the maps checkbox
  3. Click Create A New Project
  4. Once you’ve named your project (whatever you want) you can set up your billing info which will automatically enable your the API and generate the API key.

PS: Do not be hesitant of adding your billing info as the Google cloud platform offers you a 12-month free trial period and will not bill you after the trial period until you give your permission.

Project Setup

For some quick setup, we are going to use facebook’s create-react-app which saves us the hassle of having to configure webpack or babel.

So go on ahead and run this command

npm i -g create-react-app
create-react-app my-googlemap
cd my-googlemap

Before we add any code, let’s go ahead and install our dependency.

npm install --save google-maps-react

Let’s go on and edit our src folder and remove files and imports that we do not need ie

  1. Simply click on the Get Started button
  2. Tick on the maps checkbox
  3. Click Create A New Project
  4. Once you’ve named your project (whatever you want) you can set up your billing info which will automatically enable your the API and generate the API key.

Time to create our component.

We will need to edit our App.js file and instead have our component that will load our google map.

import React, { Component } from 'react';
import { Map, GoogleApiWrapper } from 'google-maps-react';

const mapStyles = {
  width: '100%',
  height: '100%'
};

export class MapContainer extends Component {
  render() {
    return (
      <Map
        google={this.props.google}
        zoom={14}
        style={mapStyles}
        initialCenter={{
         lat: -1.2884,
         lng: 36.8233
        }}
      />
    );
  }
}

export default GoogleApiWrapper({
  apiKey: 'YOUR_GOOGLE_API_KEY_GOES_HERE'
})(MapContainer);

For a simple Google Map, this is literally all the code you need. Go ahead and run your app and ensure that the map loads to the browser.

PS: Do not be hesitant of adding your billing info as the Google cloud platform offers you a 12-month free trial period and will not bill you after the trial period until you give your permission.
The GoogleApiWrapper is simply a Higher Order Component(HOC) that provides wrapper around Google APIs. Alternatively, the GoogleApiWrapper HOC can be configured by passing a function that will be called with the wrapped component’s props and should return the configuration object like so.

export default GoogleApiWrapper(
  (props) => ({
    apiKey: props.apiKey
  }
))(MapContainer)

Markers and infoWindow

Wouldn’t it be exciting to have a Marker and an infoWindow on our map showing our set initialCenter position? So let’s add this functionality to our code.

First we need to import Marker and infoWindow components from the google-maps-react library inorder to help us achieve loading of the two.

import { GoogleApiWrapper, InfoWindow, Marker } from 'google-maps-react';

Notice that our component before was stateless?, We need to add state for state management.

[...]

export class MapContainer extends Component {
   state = {
    showingInfoWindow: false,  //Hides or the shows the infoWindow
    activeMarker: {},          //Shows the active marker upon click
    selectedPlace: {}          //Shows the infoWindow to the selected place upon a marker
  };

Next, we need to add event handlers for when the map and the marker are clicked.

  onMarkerClick = (props, marker, e) =>
    this.setState({
      selectedPlace: props,
      activeMarker: marker,
      showingInfoWindow: true
    });

  onClose = props => {
    if (this.state.showingInfoWindow) {
      this.setState({
        showingInfoWindow: false,
        activeMarker: null
      });
    }
  };

PS: Do not be hesitant of adding your billing info as the Google cloud platform offers you a 12-month free trial period and will not bill you after the trial period until you give your permission.* Prerequisite:

Let’s complete our component by adding our Marker and InfoWindow components to our render method

  render() {
    return (
      <Map
        google={this.props.google}
        zoom={14}
        style={style}
        initialCenter={{ lat: -1.2884, lng: 36.8233 }
      >
        <Marker
          onClick={this.onMarkerClick}
          name={'Kenyatta International Convention Centre'}
        />
        <InfoWindow
          marker={this.state.activeMarker}
          visible={this.state.showingInfoWindow}
          onClose={this.onClose}
        >
          <div>
            <h4>{this.state.selectedPlace.name}</h4>
          </div>
        </InfoWindow>
      </Map>
    );
  }
}

[...]

Run your app and ensure you have the one marker with the infoWindow upon click.

Browser’s current location

Let’s spice things up by having our map pick our browser’s current location. We will be using navigator which is a read-only property that returns a Geolocation object that gives Web content access to the location of the device.

In our src folder create a new file and name it Map.js and create a component named CurrentLocation this is where all our functionality to pick our browser’s location will lie.

We will begin by adding some default props to our CurrentLocation component, since we will need to set the map with a center incase the current location is not provided.This is handled by the boolean prop centerAroundCurrentLocation

import React from 'react';
import ReactDOM from 'react-dom';

const mapStyles = {
  map: {
    position: 'absolute',
    width: '100%',
    height: '100%'
  }
};

export class CurrentLocation extends React.Component {

[...]

}
export default CurrentLocation;

CurrentLocation.defaultProps = {
  zoom: 14,
  initialCenter: {
    lat: -1.2884,
    lng: 36.8233
  },
  centerAroundCurrentLocation: false,
  visible: true
};

Next, we need to make our component stateful,

[...]

export class CurrentLocation extends React.Component {
  constructor(props) {
    super(props);

    const { lat, lng } = this.props.initialCenter;
    this.state = {
      currentLocation: {
        lat: lat,
        lng: lng
      }
    };
  }

[...]

}

Let’s also update our CurrentLocation component to cater for the instance when the Map is first loaded as we cannot solely depend upon the google API being always available, hence we need to check if it’s loaded. And also check if the browser’s current location is provided and recenter the map to it.

[...]

componentDidUpdate(prevProps, prevState) {
    if (prevProps.google !== this.props.google) {
      this.loadMap();
    }
    if (prevState.currentLocation !== this.state.currentLocation) {
      this.recenterMap();
    }
  }

[...]

Let’s define the recenterMap() function which only gets called when the currentLocation in the component’s state is updated and uses the .panTo() method on the google.maps.Map instance to change the center of the map.

[...]

 recenterMap() {
    const map = this.map;
    const current = this.state.currentLocation;

    const google = this.props.google;
    const maps = google.maps;

    if (map) {
      let center = new maps.LatLng(current.lat, current.lng);
      map.panTo(center);
    }
  }

[...]

Next, we need to handle the instance when the map has already loaded.This will be handled by the componentDidMount() Lifecycle method which will set a call back to fetch the current location.

[...]

 componentDidMount() {
    if (this.props.centerAroundCurrentLocation) {
      if (navigator && navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(pos => {
          const coords = pos.coords;
          this.setState({
            currentLocation: {
              lat: coords.latitude,
              lng: coords.longitude
            }
          });
        });
      }
    }
    this.loadMap();
  }

[...]

Notice the loadMap() function? Let’s go on ahead and define it.

[...]

loadMap() {
    if (this.props && this.props.google) {
      // checks if google is available
      const { google } = this.props;
      const maps = google.maps;

      const mapRef = this.refs.map;

      // reference to the actual DOM element
      const node = ReactDOM.findDOMNode(mapRef);

      let { zoom } = this.props;
      const { lat, lng } = this.state.currentLocation;
      const center = new maps.LatLng(lat, lng);
      const mapConfig = Object.assign(
        {},
        {
          center: center,
          zoom: zoom
        }
      );

      // maps.Map() is constructor that instantiates the map
      this.map = new maps.Map(node, mapConfig);
    }
  }

Basically, the loadMap() function is only called after the component has been rendered and grabs a reference to the DOM component to where we want our map to be placed.

Our CurrentLocation component is almost looking up, But we need to ensure that our previous Marker picks our currenct location ie the browsers current location and so we need to introduce Parent-Child concept through the renderChildren() method which will be responsible for actually calling the method on the child component.

Read more about Parent-Child communication here

[...]

 renderChildren() {
    const { children } = this.props;

    if (!children) return;

    return React.Children.map(children, c => {
      if (!c) return;
      return React.cloneElement(c, {
        map: this.map,
        google: this.props.google,
        mapCenter: this.state.currentLocation
      });
    });
  }

[...]

And finally, let’s add our render() method

[...]

render() {
     const style = Object.assign({}, mapStyles.map);
    return (
      <div>
        <div style={style} ref="map">
          Loading map...
        </div>
        {this.renderChildren()}
      </div>
    );
  }

[...]

Lastly, before we wind up we need to update our MapContainer component to include our new changes. So let’s change it to this

import React, { Component } from 'react';
import { GoogleApiWrapper, InfoWindow, Marker } from 'google-maps-react';

import CurrentLocation from './Map';

export class MapContainer extends Component {
  state = {
    showingInfoWindow: false,
    activeMarker: {},
    selectedPlace: {}
  };

  onMarkerClick = (props, marker, e) =>
    this.setState({
      selectedPlace: props,
      activeMarker: marker,
      showingInfoWindow: true
    });

  onClose = props => {
    if (this.state.showingInfoWindow) {
      this.setState({
        showingInfoWindow: false,
        activeMarker: null
      });
    }
  };

  render() {
    return (
      <CurrentLocation
        centerAroundCurrentLocation
        google={this.props.google}
      >
        <Marker onClick={this.onMarkerClick} name={'current location'} />
        <InfoWindow
          marker={this.state.activeMarker}
          visible={this.state.showingInfoWindow}
          onClose={this.onClose}
        >
          <div>
            <h4>{this.state.selectedPlace.name}</h4>
          </div>
        </InfoWindow>
      </CurrentLocation>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: 'YOUR_GOOGLE_API_KEY_GOES_HERE'
})(MapContainer);

Run your app; heading over to our browser, our map should first load with our initialCenter then reload to pick our browser’s current location with the marker positioned to this location and Voilà we are done.

Conclusion

In this article we’ve been able to load our google maps React component, add a marker and have an infoWindow onto it and also have the map pick our current location. While we did not dive into adding more functionalities to our map such as, having polylines and polygons or adding event listeners, I highly recommend that you look into them

Learn More

Full Stack Developers: Everything You Need to Know

React Hooks Tutorial for Beginners: Getting Started With React Hooks

Learn React.js for Beginners

Learn React - React Crash Course 2019 - React Tutorial with Examples

React Router: Add the Power of Navigation

React - The Complete Guide (incl Hooks, React Router, Redux)

Modern React with Redux [2019 Update]

React Native - The Practical Guide

Kotlin For Android Developers: Top 7 Android Apps Written In Kotlin You Should Know

Kotlin For Android Developers: Top 7 Android Apps Written In Kotlin You Should Know

Looking for Kotlin for Android Developers? or Want to Develop Android apps with Kotlin?Read the following article about understanding Kotlin & 7 application built with kotlin.

Looking for Kotlin for Android Developers? or Want to Develop Android apps with Kotlin?Read the following article about understanding Kotlin & 7 application built with kotlin.

Writer’s Note: For all the aspiring developers reading this blog you are in for a treat. For the non-nerd entrepreneurs, I won’t bore you with technical jargons; instead I’ll introduce you to Kotlin in the simplest way possible

A Brief History of Kotlin: (How did this beast come to exist?)

In July of 2011, a very smart group of individuals (collectively known as JetBrains) unveiled to the world their prized invention, Kotlin.

Kotlin for Android developers has become a token of excellence ever since. It was only 5 years later that the first official version 1.0 released in 2016. The most recent Kotlin version is 1.3.10 released in November of 2018.

(A Tip For Entrepreneurs: If any company tries to pull a fast one on you just ask them which version they are using currently. Ask a bit technical questions to show them who’s the boss, but do slight research beforehand.)

Kotlin becomes the Primary Choice: (Why Google made Kotlin their Number 1?)

Andrey Breslav (father of Kotlin) said that Kotlin for Android developers is designed to be an industrial-strength object-oriented language, and a “better language” than Java, and they proved it all the way through. Features like Interoperability with Java, Conciseness, and Android Studio support were reasons enough for Google to make the official switch from Java to Kotlin. But they hit jackpot with this new language (also considered as the Swift of Android).

(A Tip For Developers: Great companies and startups like Google, Netflix, Uber, and many others are already using code base of Kotlin. It’s a great time to make the jump and migrate from Java to Kotlin.)

7 Apps Written in Kotlin ( Kotlin Examples )

If you don’t believe me then trust these 7 world-class brands that have built their Mobile app using Kotlin. Here are the famous android apps built using Kotlin:

1. Pinterest

It is by far the most famous photo-sharing social platform. So when Pinterest made the jump from Java to Kotlin in 2016 they set a huge example for other companies. Pinterest showcased the benefits they received from going with Kotlin at the Droidcon NYC 2016. One amazing thing is that Pinterest made the change to Kotlin even before Google announced the first-class support for Kotlin. These facts make Pinterest probably the best kotlin android example on this list.

2. Trello

Atlassian owned project-management application; Trello has been helping many companies and individuals with their working process. As per the recent announcement by Atlassian; Kotlin will be the programming language.. Efficient interoperability between Java and Kotlin was the reason to go with Kotlin. This decision made Trello an overnight favorite on Google Play with an average 4.5 rating from 69,000+ reviews.

3. Coursera

Coursera provides online courses by remarkable universities and institutes such as Stanford and Yale. It’s an educational company providing open online courses that didn’t have separate Android and iOS organizations. They only had the concept of mobile and that’s why they decided to start using Kotlin. It’s similar to Swift hence resulting in easier knowledge sharing between engineers, better communication, and more efficient overall development.

4. Twidere

Twidere is a fully designed Twitter browser that enhances the user experience of the Twitter platform. It is an open source Twitter client app used to customize themes, filter unwanted tweets, manage multiple accounts, and do many other things. Twidere is the perfect combination of Kotlin and Java code. The simplicity and smooth performance of this app have earned it 1600+ stars on Github and 100,000+ downloads from Google Play.

5. Shadowsocks

Shadowsocks is a cross-platform secured SOCKS5 proxy app. The app helps its users to access the internet privately and safely. The app provides an industry-level encryption algorithm and it’s optimized for mobile devices and wireless networks. Shadowsocks is a staggering success with 13,000+ stars Github and an average rating of 4.6 on Google Play Store from 52,000+ reviews.

6. Square

Square, the online payment platform announced their approval to use Kotlin for Android developers internally for their app development projects in 2015. Since then, Square has been in love with Kotlin and what it can do. Many of you must know what a big name Square is in the online payment industry. So their decision of going with Kotlin has set an example for many startups and enterprises.

7. Evernote

Evernote is an advanced version of Trello with a lot more features. With features like organizing, task lists, note-taking, and archiving Evernote decided to integrate Kotlin into their Android client. Kotlin has made the Android app development very easy and flexible. Due to this amazing additional features became possible like input typed notes, scan handwritten notes, images, web pages, add to-do’s, photos, and even audio.

Why you should go for Kotlin Android App Development
    1. Even if you don’t know anything about Kotlin, you can still set up a Kotlin for Android developers Kotlin project without any problem.
    1. Kotlin is faster to write, hence; saving time and resources in creating an Android app.
    1. You can do many things like debug without issues, run from the IDE, and use the instant run among many other things.
    1. Moreover; JetBrains and Google are the two huge companies working on Kotlin to make it a nest for long-term Android development.
    1. Kotlin solved the null point exception trouble by having null right in its type system making the code less prone to errors and more stable.
    1. Kotlin has many new features like continuous library size optimization, various Kotlin Android extensions, and libraries like Anko.
    1. Any device that can run JVM will be able to use Kotlin virtually.
    1. A developer can also use Kotlin for front-end development for any version higher than Kotlin 1.1
    1. With Gradle support, coders can write their Gradle files in Kotlin and with Kotlin native the future is open for any platform.
Conclusion

Kotlin is on the rise and it won’t be stopping any time soon. It is the bright new future of Android app development and if you wish to be part of the future then you better tighten your belt and make a run towards Kotlin. If you wish to make a big name in the Android market, find a reliable development team offering Kotlin app development services for your projects or hire Kotlin developers of top caliber. For the developers who wish to build an Android App in Kotlin, this is the time to join such companies.

Build Native Android Apps with Kotlin

Build Native Android Apps with Kotlin

Learn to build native Android apps with Kotlin. You will also learn how to use Android Jetpack, Firebase, Room, MVVM, Navigation, LiveData, and Kotlin Coroutines. This full course explains how to build an entire Android app using best practices.

Learn to build native Android apps with Kotlin. You will also learn how to use Android Jetpack, Firebase, Room, MVVM, Navigation, LiveData, and Kotlin Coroutines. This full course explains how to build an entire Android app using best practices.

⭐️ Course Contents ⭐️

1
(0:00) Introduction

2
(5:14) Model View ViewModel (MVVM) Architecture fundamentals and variations
(5:38) Is MVVM the perfect architecture?
(7:41) Overview of MVVM with whiteboard example
(12:11) Pros and Cons of MVVM
(18:58) Package structure

3
(23:22) How to create Vector Drawables
(24:22) Difference between Raster (PNG, JPG, BMP) and Vector (SVG) Images?
(27:55) Uh Oh!
(28:41) How to use Inkscape to create an SVG from a BMP/PNG
(30:07) How to convert an SVG into an Android Studio Vector Asset
(32:29) How to create simple animations using animation lists and fade animations

4
(38:19) Material Design User Interface using ConstraintLayout and Styles
(41:00) Building an XML Layout using ConstraintLayout
(51:09) Using ConstraintLayout Chains
(55:43) Some tips on using Styles to create a material design look

5
(56:51) How to use (and when not to use) the Android Navigation Component from Android Jetpack
(1:00:00) Adding Safe Args to gradle
(1:01:15) Building a Navigation Graph using the Navigation Editor (XML)
(1:11:00) Creating a NavHostFragment to host the Navigation Component and adding it to an Activity
(1:15:29) How to actually change destinations in our Fragments using the Navigation Component (with safe args)

6
(1:20:00) Setting up Fragments as Views in MVVM using Kotlin Synthetic Properties
(1:25:32) Starting point
(1:27:54) Importing an XML layout to an Activity/Fragment using Kotlin Synthetic Properties
(1:32:09) How to reference Views in the Fragment using synthetic properties
(1:33:41) Adding onClickListener to our views
(1:38:03) Intercepting OnBackPressed (NOTE: The API for this has changed since making this video. I have updated the Repository appropriately)
(1:39:40) How to observe the ViewModel using LiveData callbacks

7
(1:43:22) ViewModels in MVVM with Kotlin Coroutines for Concurrency
(1:45:26) A look at my BaseViewModel class which contains part of the Coroutines Implementation (Coroutine Scope)
(1:49:25) Starting point
(2:01:40) Handling events from the View in the ViewModel
(2:05:34) Using the launch Coroutine Builder to access data
(2:08:44) How to update the MutableLiveData fields to publish data to the View

8
(2:19:35) Modern RecyclerView implementation using LiveData to handle ItemTouchListener() callbacks
(2:22:49) Overview of the RecyclerView within the XML View with LinearLayoutManager
(2:26:53) What does the DiffUtil do?
(2:28:48) A look at the source code of ListAdapter to better understand how it works
(2:35:34) Writing the RecyclerView.ViewHolder class
(2:37:23) Why is it actually called a RecyclerView? What gets Recycled?
(2:37:58) Writing our RecyclerView.ListAdapter
(2:46:37) How to use a MutableLiveData object to publish events from the onClickListener in the ViewHolders
(2:48:09) Overview of the Fragment which manages the RecyclerView, and how to avoid memory leaks!

9
(2:53:17) FirebaseAuth for User Authentication using Google Sign In
(2:54:00) How to set up a new Firebase Project using Android Studio
(2:54:36) Enabling Authentication (FirebaseAuth) in the Firebase Console
(2:55:00) Setting up a debug signing certificate for your App in Firebase
(2:56:48) Gradle Configurations for FirebaseAuth
(2:58:00) Setting up GoogleSignInProvider
(2:59:24) Handling the result in onActivityResult
(3:01:06) Back FirebaseAuth Implementation using Coroutines

10
(3:05:31) Local Database with Room Persistence Library and Coroutines
(3:06:17) Entities and Primary Keys in Room
(3:08:50) Setting up a Dao (Data Access Object) in Room
(3:12:28) Overview of RoomDatabase implementation
(3:14:21) How to build your Database and get a reference to you Dao
(3:14:47) How to get data in and out of the Dao using suspend functions

11
(3:16:34) Setting up a Local and Remote Database using Firebase's Firestore NoSQL library
(3:17:33) Communicating with Firestore using a Repository, with Coroutines

12
(3:21:59) Dependency Injection using an AndroidViewModel, and ViewModelProvider.Factory
(3:22:29) What is dependency injection in simple terms?
(3:23:36) Implementing Dependency Injection using AndroidViewModel
(3:24:13) Quick look at using a ViewModelProvider.Factory to create our ViewModel with the Injected Repository
(3:24:27) How to use our Dependency Injector from within a Fragment or Activity

💻 Code: https://github.com/BracketCove/SpaceNotes