我想创建一个项目,我需要集成谷歌地图API.我需要自动完成,本地化并在地图上绘制路线.我怎么能用角度做这个,你能为我推荐一个图书馆吗?或者我如何使用谷歌地图api为javascript做到这一点.该项目使用yeoman-fullstack生成.
谢谢.
首先,如果您想使用AngularJS获得Google Maps API,您有两个解决方案:
使用Scratch中的Google Maps API
使用Angular-Google-Maps
我将向您展示如何从头开始轻松实现.
这是一个简单的AngularJS应用程序的示例,仅用于学习使用此类API.我已经完成了这个小小的AngularJS练习,以便在更大的应用程序中使用它.
index.html的:
AngularJS-Google-Maps
app.js:
var myApp = angular.module("myApp",[]); //Getting our Maps Element Directive myApp.directive("myMaps", function(){ return{ restrict:'E', //Element Type template:'', //Defining myApp div replace:true, //Allowing replacing link: function(scope, element, attributes){ //Initializing Coordinates var myLatLng = new google.maps.LatLng(YourLat,YourLong); var mapOptions = { center: myLatLng, //Center of our map based on LatLong Coordinates zoom: 5, //How much we want to initialize our zoom in the map //Map type, you can check them in APIs documentation mapTypeId: google.maps.MapTypeId.ROADMAP }; //Attaching our features & options to the map var map = new google.maps.Map(document.getElementById(attributes.id), mapOptions); //Putting a marker on the center var marker = new google.maps.Marker({ position: myLatLng, map: map, title:"My town" }); marker.setMap(map); //Setting the marker up } }; });
style.css中:
//Just giving our container Height and Width + A Red border #map-canvas{ height: 400px; width: 700px; border: 2px solid red; }
这只是启动它的一个非常基本的方法,我甚至没有使用控制器,即使你真的应该在AngularJS中使用它们.
这是一个工作的Plunk我忍受了这个代码.
您可以通过多种不同的方式使用Google Maps API,只需查看文档或在StackOverflow上.
现在,如果您想管理2个位置,标记等之间的路线,您应该看看:
Google Maps API文档
这个答案来自@geocodezip
这个答案来自@Gurpreet Singh
这个答案来自@ zeeshan0026
最后,您可以使用Polylines(您想要的长途路线)查看由@Shreerang Patwardhan制作的这个有效的JSFiddle.
对于将来的实现,请确保将myMaps.js指令放在一个单独的文件中并在App模块中注入它具有依赖关系为了使用相同的工作指令作为起始点来获取DRY(不要重复自己)和可维护的应用程序您的Angular应用程序涉及谷歌地图.例如,您可以只更改坐标或添加一些新地图的选项,以启动未来需要Google地图的应用程序.
你应该得到类似的东西:
myApp.directive("myMap", function(){ . . . }); //Goes in a Separated File var myApp = angular.module("myApp",['myMaps']); //Dependency Injection
我希望我一直很有帮助.