如何添加标记到谷歌地图angular2?

时间:2017-09-12 15:57:05

标签: angular google-maps typescript google-maps-api-3

我有一个组件,其中包含用于添加lng和lat的表单。我用于在OnInit中初始化map的主要组件。 如何动态地向地图添加新标记?

我的组件有地图:

import { Component, OnInit, Input } from '@angular/core';
import { PartyService } from './services/party.service';
import { Party } from './classes/party';
declare let google: any;
declare let map: any;

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
   parties: Party[] = [];
   party_location: Location[] = [];

   constructor(private partyService: PartyService) { }

   ngOnInit() {
     map = new google.maps.Map(document.getElementById('map'), {
      center: { lat: -25.363, lng: 131.044 },
      scrollwheel: true,
      zoom: 16
    });



if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    let pos = {
      lat: position.coords.latitude,
      lng: position.coords.longitude
    };

    infoWindow.setPosition(pos);
    infoWindow.setContent('This is you.');
    infoWindow.open(map);
    map.setCenter(pos);
  });
}

let infoWindow = new google.maps.InfoWindow;

 }
}

1 个答案:

答案 0 :(得分:0)

让我们说你是新coordinates,以下内容会在地图上添加新标记

      let marker = new google.maps.Marker({
        position: {lat:<yourLatitude>,lng:<yourLong>}
        map: map 

      });

在现有代码中,您可以修改为:

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    let pos = {
      lat: position.coords.latitude,
      lng: position.coords.longitude
    };
    let marker = new google.maps.Marker({
        position: {lat:<yourLatitude>,lng:<yourLong>}
        map: map 

      });
    infoWindow.setPosition(pos);
    infoWindow.setContent('This is you.');
    infoWindow.open(map);
    map.setCenter(pos);
  });
}