paulobunga
paulobunga

Reputation: 385

Set Multiple markers with Angular 4 and google maps

Hello Everyone need Help setting Multiple markers to google map component in Angular 4. I can get a single Marker to show up with this code.

 ngOnInit() {
    const myLatlng = new google.maps.LatLng(40.748817, -73.985428);
    const mapOptions = {
        zoom: 13,
        center: myLatlng,
        scrollwheel: false

    };
    const map = new google.maps.Map(document.getElementById('map'), mapOptions);
    const Marker = new google.maps.Marker({
        position: myLatlng,
        title: 'Hello World!'
    });
    // To add the marker to the map, call setMap();
    Marker.setMap(map);


}

How can I modify this to show multiple locations. I have locations in from JSON like below.

    {
        "locations": [
            {
                "_id": "59eb784fa8e0be0004fb466e",
                "updatedAt": "2017-10-21T16:39:43.338Z",
                "createdAt": "2017-10-21T16:39:43.338Z",
                "latitude": "0.2346285",
                "longitude": "32.4352628",
                "locationName": "Prime warehouse A",
                "locationInfo": "Kampala Warehouse #001",
                "__v": 0
            },
            {
                "_id": "1568eb54560be000456466e",
                "updatedAt": "2018-10-21T16:39:43.448Z",
                "createdAt": "2016-09-11T16:39:43.338Z",
                "latitude": "4.3346285",
                "longitude": "32.4352628",
                "locationName": "Prime warehouse A",
                "locationInfo": "Kampala Warehouse #001",
                "__v": 0
            }
        ]
    }

Upvotes: 1

Views: 4386

Answers (1)

syciphj
syciphj

Reputation: 996

As long as you can access your locations array, then you can loop through it and from there create a marker each.

Here's a sample if you put everything in your ngOnInit function:

ngOnInit() {
  let map;
  const locations; // if you have your locations hard-coded, else just make sure it's accessible

  const myLatlng = new google.maps.LatLng(40.748817, -73.985428);
  const mapOptions = {
    zoom: 13,
    center: myLatlng,
    scrollwheel: false

};

  map = new google.maps.Map(document.getElementById('map'), mapOptions);


  // loop through each object of your locations array
  for (let location in locations) {

    // The marker's position property needs an object like { lat: 0, lng: 0 };
    // Number(location.latitude) is there to convert the string to a number, but if it's a number already, there's no need to cast it further.
    let latLng = {lat: Number(location.latitude), lng: Number(location.longitude)};

    // Set the position and title
    let marker = new google.maps.Marker({
      position: latLng,
      title: location.locationName
  })

    // place marker in map
    marker.setMap(map)
  }
}

You can learn more about importing data into a Map with Google's official documentation

Hope that helps!

Upvotes: 4

Related Questions