简体   繁体   English

如何在Google Map Angle2中添加标记?

[英]how to add marker to google map angular2?

I have a component with form for adding lng and lat. 我有一个组件,用于添加lng和lat。 My main component I use for initialize map in OnInit. 我的主要组件用于OnInit中的初始化映射。 How can I add new markers dynamically to my map? 如何向地图动态添加新标记?

My component with 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;

 }
}

Let's say you've new coordinates , the following will add new marker on your map 假设您有新coordinates ,以下将在地图上添加新标记

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

      });

In your existing code, you can modify as: 在现有代码中,您可以修改为:

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);
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM