标记定制和定向API [英] Marker customization and direction API

查看:115
本文介绍了标记定制和定向API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google地图在我的应用程序中显示方向。我想定制标记以显示比仅显示位置名称(即城市,州和其他邮政编码)的默认文本更多的文本。我的想法是在标记泡泡上添加自定义文字。这是我迄今为止尝试过的代码。
注意:我试图添加标记但不起作用。并且还可以使用数据库中的json获取填充地图的数据。

代码:

  var directionDisplay; 
var directionsService = new google.maps.DirectionsService();
var map;

函数initialize(){
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033,-87.6500523);
var myOptions = {
zoom:7,
mapTypeId:google.maps.MapTypeId.ROADMAP,
center:chicago
}
map = new google .maps.Map(document.getElementById(map_canvas),myOptions);
directionsDisplay.setMap(map);


函数calcRoute(){
//获取路由号
var request ='';
var route_no =($(。route_no)。attr('id')); $ b $ .ajax({
type:'POST',
url:base_url +index.php / routes / getMapData,
data:{
route:route_no
},
success:function(data){
//alert(JSON.stringify(data[0].waypoints))
var datavalues ='';
datavalues = data [0];
var wypt = [];

$ .each(datavalues.waypoints,function(index,value){
{
wypt.push({location:value.location,stopover:value.stopover})

}
});



request = {

origin:+ data [0] .origin +,
destination:+ data [0] .destination +,
waypoints:wypt ,
travelMode:google.maps.DirectionsTravelMode.DRIVING
}
//添加记号
var mark = [] ;
$ .each(datavalues.title,function(index,value){
mark.push({location:value.location,title:value.company})
});

var marker = new google.maps.Marker(mark);
marker.setMap(map);
directionsService.route(request,function(response,status){
if(status == google.maps.DirectionsStatus.OK){
directionsDisplay.setDirections(response);
}
});
返回false;
},
dataType:'json'
})

}

示例JSON结果:

  [{origin:Mantachie MS 38855,目的地:Mantachie MS 38855,航点:[{停留:真实,位置:JACKSON TN 38305},{停留:true,位置:上层SANDUSKY ON 43351} ],title:[{company:TBMS,location:Mantachie MS 38855},{company:ARJ MANUFACTURING,location:JACKSON TN 38305},{公司:BRIDGESTONE,location:UPPER SANDUSKY ON 43351},{company:TBMS,location:Mantachie MS 38855}]}] 

我想在城市和州的标记上显示公司名称。



这里是一个示例地图,由谷歌显示如何方向API工作。

解决方案

下面是一个自定义图标的示例,infowindow中的文本并向侧栏添加条目: http://www.geocodezip.com/v3_directions_custom_iconsC.html



代码段:

//此变量将收集最终放置在side_bar var side_bar_html =; var gmarkers = []; var map = null; var startLocation = null; var endLocation = null;函数initialize(){var center = new google.maps.LatLng(24.7756,121.0062); map = new google.maps.Map(document.getElementById('map_canvas'),{center:center,zoom:13,mapTypeId:google.maps.MapTypeId.ROADMAP}); google.maps.event.addListener(map,'click',function(){infowindow.close();}); var directionsService = new google.maps.DirectionsService(); var request = {origin:532 Beacon St.,Boston,MA,目的地:马萨诸塞州剑桥77马萨诸塞大道77号,travelMode:google.maps.DirectionsTravelMode.WALKING}; var polyline = new google.maps.Polyline({path:[],strokeColor:'#FF0000',strokeWeight:3}); directionsService.route(request,function(response,status){if(status == google.maps.DirectionsStatus.OK){var bounds = new google.maps.LatLngBounds(); var route = response.routes [0]; var summaryPanel = document.getElementById(directions_panel); var detailsPanel = document.getElementById(direction_details); startLocation = new Object(); endLocation = new Object(); summaryPanel.innerHTML =; detailsPanel.innerHTML ='< ; ul>'; //对于每个路由,显示摘要信息for(var i = 0; i< route.legs.length; i ++){var routeSegment = i + 1; summaryPanel.innerHTML + =< b> ; Route Segment:+ routeSegment +< / b>< br />; summaryPanel.innerHTML + = route.legs [i] .start_address +to; summaryPanel.innerHTML + = route.legs [i ] .end_address +< br />; summaryPanel.inn erHTML + = route.legs [i] .distance.text +< br />< br />; } var path = response.routes [0] .overview_path; var legs = response.routes [0] .legs; for(i = 0; i< legs.length; i ++){if(i == 0){startLocation.latlng = legs [i] .start_location; startLocation.address = legs [i] .start_address; createMarker(legs [i] .start_location,start,legs [i] .start_address,green); } endLocation.latlng = legs [i] .end_location; endLocation.address = legs [i] .end_address; var steps = legs [i] .steps; for(j = 0; j

  html {height:100%} body {height:100%; margin:0px;  

< script src =http://maps.google.com/maps/api/js>< / script>< div id =map_canvasstyle =float:left; width:70%; height :100%;>< / div>< div id =control_panelstyle =float:right; width:30%; text-align:left; padding-top:20px> < table border =1> < TR> < TD> < div id =directions_panelstyle =margin:20px; background-color:#FFEE77;>< / div> < / TD> < / TR> < TR> < TD> < div id =direction_detailsstyle =margin:20px;>< / div> < / TD> < / TR> < TR> < TD> < div id =side_barstyle =margin:20px;>< / div> < / TD> < / TR> < / table>< / div>

I am using Google Maps to display direction in my application. I would like to customize the markers to display more text than the default which shows only the position name i.e the city,state and in others zip code. My idea is to add customized text on the marker bubble. Here is my code in what I have tried so far. Note: I have tried to add markers but are not working. And also data to populate the map is obtained using json from db. I have posted sample result after the code.

Code:

  var directionDisplay;
  var directionsService = new google.maps.DirectionsService();
  var map;

  function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var chicago = new google.maps.LatLng(41.850033, -87.6500523);
    var myOptions = {
      zoom:7,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: chicago
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
  }

  function calcRoute() {
     // get route no
     var request='';
     var route_no=($(".route_no").attr('id')); 
     $.ajax({
         type: 'POST',
         url: base_url+"index.php/routes/getMapData",
         data: {
            route: route_no
         },
         success: function(data){
             //alert(JSON.stringify(data[0].waypoints))
             var datavalues='';
             datavalues=data[0];
             var wypt=[];

                    $.each(datavalues.waypoints,function(index,value){
                    {
                      wypt.push({location: value.location,stopover: value.stopover})

                    }
                });



             request={

                 origin:""+data[0].origin+"",
                 destination:""+data[0].destination+"",
                   waypoints:  wypt,
                 travelMode: google.maps.DirectionsTravelMode.DRIVING
             }
        //Add marker
        var mark=[]; 
                $.each(datavalues.title,function(index,value){
                    mark.push({location:value.location,title: value.company})
                });

               var marker= new google.maps.Marker( mark );
                marker.setMap(map);
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
             return false;
         },
         dataType: 'json'         
     })

  }

Sample JSON result:

[{"origin":"Mantachie MS 38855","destination":"Mantachie MS 38855","waypoints":[{"stopover":true,"location":"JACKSON TN 38305"},{"stopover":true,"location":"UPPER SANDUSKY ON 43351"}],"title":[{"company":"TBMS","location":"Mantachie MS 38855"},{"company":"ARJ MANUFACTURING","location":"JACKSON TN 38305"},{"company":"BRIDGESTONE","location":"UPPER SANDUSKY ON 43351"},{"company":"TBMS","location":"Mantachie MS 38855"}]}]

I would like to display the company names on the markers too alongside the city and states.

Here is a sample map by google showing how the direction API work.

解决方案

Here is an example which customizes the icon, the text in the infowindow and adds an entry to the sidebar: http://www.geocodezip.com/v3_directions_custom_iconsC.html

code snippet:

       // this variable will collect the html which will eventually be placed in the side_bar 
      var side_bar_html = "";

      var gmarkers = [];
      var map = null;
      var startLocation = null;
      var endLocation = null;

      function initialize() {
        var center = new google.maps.LatLng(24.7756, 121.0062);

        map = new google.maps.Map(document.getElementById('map_canvas'), {
          center: center,
          zoom: 13,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        google.maps.event.addListener(map, 'click', function() {
          infowindow.close();
        });

        var directionsService = new google.maps.DirectionsService();
        var request = {
          origin: "532 Beacon St., Boston, MA",
          destination: "77 Massachusetts Ave, Cambridge, MA",
          travelMode: google.maps.DirectionsTravelMode.WALKING
        };

        var polyline = new google.maps.Polyline({
          path: [],
          strokeColor: '#FF0000',
          strokeWeight: 3
        });

        directionsService.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            var bounds = new google.maps.LatLngBounds();
            var route = response.routes[0];
            var summaryPanel = document.getElementById("directions_panel");
            var detailsPanel = document.getElementById("direction_details");
            startLocation = new Object();
            endLocation = new Object();

            summaryPanel.innerHTML = "";
            detailsPanel.innerHTML = '<ul>';

            // For each route, display summary information.
            for (var i = 0; i < route.legs.length; i++) {
              var routeSegment = i + 1;
              summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
              summaryPanel.innerHTML += route.legs[i].start_address + " to ";
              summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
              summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
            }
            var path = response.routes[0].overview_path;
            var legs = response.routes[0].legs;
            for (i = 0; i < legs.length; i++) {
              if (i == 0) {
                startLocation.latlng = legs[i].start_location;
                startLocation.address = legs[i].start_address;
                createMarker(legs[i].start_location, "start", legs[i].start_address, "green");
              }
              endLocation.latlng = legs[i].end_location;
              endLocation.address = legs[i].end_address;
              var steps = legs[i].steps;
              for (j = 0; j < steps.length; j++) {
                var nextSegment = steps[j].path;
                detailsPanel.innerHTML += "<li>" + steps[j].instructions;
                var dist_dur = "";
                if (steps[j].distance && steps[j].distance.text) dist_dur += "&nbsp;" + steps[j].distance.text;
                if (steps[j].duration && steps[j].duration.text) dist_dur += "&nbsp;" + steps[j].duration.text;
                if (dist_dur != "") {
                  detailsPanel.innerHTML += "(" + dist_dur + ")<br /></li>";
                } else {
                  detailsPanel.innerHTML += "</li>";

                }
                for (k = 0; k < nextSegment.length; k++) {
                  polyline.getPath().push(nextSegment[k]);
                  bounds.extend(nextSegment[k]);



                }
              }
            }

            detailsPanel.innerHTML += "</ul>"
            polyline.setMap(map);
            map.fitBounds(bounds);
            createMarker(endLocation.latlng, "end", endLocation.address, "red");
            // == create the initial sidebar ==
            makeSidebar();

          }
        });
      }
      var icons = new Array();
      icons["red"] = {
        url: "http://maps.google.com/mapfiles/ms/micons/red.png",
        // This marker is 32 pixels wide by 32 pixels tall.
        size: new google.maps.Size(32, 32),
        // The origin for this image is 0,0.
        origin: new google.maps.Point(0, 0),
        // The anchor for this image is at 16,32.
        anchor: new google.maps.Point(16, 32)
      };

      function getMarkerImage(iconColor) {
          if ((typeof(iconColor) == "undefined") || (iconColor == null)) {
            iconColor = "red";
          }
          if (!icons[iconColor]) {
            icons[iconColor] = {
              url: "http://maps.google.com/mapfiles/ms/micons/" + iconColor + ".png",
              // This marker is 32 pixels wide by 32 pixels tall.
              size: new google.maps.Size(32, 32),
              // The origin for this image is 0,0.
              origin: new google.maps.Point(0, 0),
              // The anchor for this image is at 16,32.
              anchor: new google.maps.Point(16, 32)
            };
          }
          return icons[iconColor];

        }
        // Marker sizes are expressed as a Size of X,Y
        // where the origin of the image (0,0) is located
        // in the top left of the image.

       // Origins, anchor positions and coordinates of the marker
       // increase in the X direction to the right and in
       // the Y direction down.

      var iconImage = {
        url: 'http://maps.google.com/mapfiles/ms/micons/red.png',
        // This marker is 32 pixels wide by 32 pixels tall.
        size: new google.maps.Size(32, 32),
        // The origin for this image is 0,0.
        origin: new google.maps.Point(0, 0),
        // The anchor for this image is at 16,32.
        anchor: new google.maps.Point(16, 32)
      };
       // Shapes define the clickable region of the icon.
       // The type defines an HTML &lt;area&gt; element 'poly' which
       // traces out a polygon as a series of X,Y points. The final
       // coordinate closes the poly by connecting to the first
       // coordinate.
      var iconShape = {
        coord: [9, 0, 6, 1, 4, 2, 2, 4, 0, 8, 0, 12, 1, 14, 2, 16, 5, 19, 7, 23, 8, 26, 9, 30, 9, 34, 11, 34, 11, 30, 12, 26, 13, 24, 14, 21, 16, 18, 18, 16, 20, 12, 20, 8, 18, 4, 16, 2, 15, 1, 13, 0],
        type: 'poly'
      };
      var infowindow = new google.maps.InfoWindow({
        size: new google.maps.Size(150, 50)
      });

      function createMarker(latlng, label, html, color) {
        // alert("createMarker("+latlng+","+label+","+html+","+color+")");
        var contentString = '<b>' + label + '</b><br>' + html;
        var marker = new google.maps.Marker({
          position: latlng,
          map: map,
          icon: getMarkerImage(color),
          shape: iconShape,
          title: label,
          zIndex: Math.round(latlng.lat() * -100000) << 5
        });
        marker.myname = label;
        gmarkers.push(marker);

        google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent(contentString);
          infowindow.open(map, marker);
        });
      }

      function myclick(i) {
          google.maps.event.trigger(gmarkers[i], "click");
        }
        // == rebuilds the sidebar to match the markers currently displayed ==

      function makeSidebar() {
        var html = "";
        for (var i = 0; i < gmarkers.length; i++) {
          html += '<a href="javascript:myclick(' + i + ')">' + gmarkers[i].myname + '<\/a><br>';
        }
        document.getElementById("side_bar").innerHTML = html;
      }
      google.maps.event.addDomListener(window, 'load', initialize);

html {
  height: 100%
}
body {
  height: 100%;
  margin: 0px;
  padding: 0px
}
#map_canvas {
  height: 100%
}

<script src="http://maps.google.com/maps/api/js"></script>
<div id="map_canvas" style="float:left;width:70%;height:100%;"></div>
<div id="control_panel" style="float:right;width:30%;text-align:left;padding-top:20px">
  <table border="1">
    <tr>
      <td>
        <div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
      </td>
    </tr>
    <tr>
      <td>
        <div id="direction_details" style="margin:20px;"></div>
      </td>
    </tr>
    <tr>
      <td>
        <div id="side_bar" style="margin:20px;"></div>
      </td>
    </tr>
  </table>
</div>

这篇关于标记定制和定向API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆