如何在Google地图API中发送静态消息 [英] How to give static message in google map API

查看:121
本文介绍了如何在Google地图API中发送静态消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用谷歌地图API,它工作正常,就像在这张地图上,如果我点击一个标记,一个对话框打开显示的位置地址;而不是我想显示一个静态值。我怎样才能改变我的代码来做到这一点?

function initMap(){ var directionsDisplay = new google.maps.DirectionsRenderer; var directionsService = new google.maps.DirectionsService; var map = new google.maps.Map(document.getElementById('map'),{zoom:14,center:{lat:12.9577129,lng:77.6764937} // Starting Point Marathahalli}); directionsDisplay.setMap(地图); calculateAndDisplayRoute(directionsService,directionsDisplay); }函数calculateAndDisplayRoute(directionsService,directionsDisplay){var selectedMode = document.getElementById('mode').value; / *配置航点* / var waypts = []; waypts.push({location:{lat:12.9583665,lng:77.6635659},// HAL中途停留:true},{location:{lat:12.9630167,lng:77.6268656},stopover:true}); directionsService.route({origin:{lat:12.9577129,lng:77.6764937},// Haight。destination:{lat:12.9868068,lng:77.6070679},// Ending Point Shivaji Nagar。travelMode:google.maps.TravelMode [selectedMode] ,waypoints:waypts},function(response,status){if(status =='OK'){directionsDisplay.setDirections(response); console.log(response);} else {window.alert('Directions requests failed to due '+ status);}}); }

<!DOCTYPE html>< html> < HEAD> < meta name =viewportcontent =initial-scale = 1.0,user-scalable = no> < meta charset =utf-8> < title>方向中的旅行模式< / title> <风格> / *总是显式设置地图高度来定义包含地图的div *元素的大小。 * / #map {height:100%; } / *可选:使样本页面填满窗口。 * / html,body {height:100%;保证金:0;填充:0; }#floating-panel {position:absolute;顶部:10px;左:25%; z-index:5; background-color:#fff;填充:5px;边界:1px固体#999; text-align:center; font-family:'Roboto','sans-serif'; line-height:30px; padding-left:10px; }< / style> < /头> <身体GT; < form id =testForm> < select name =tripId> < option value =>< / option> < /选择> < /形式> < div id =floating-panel> < b>旅行模式:< / b> < select id =mode> < option value =DRIVING>驾驶< / option> < /选择> < / DIV> < div id =map>< / div> < script async defer src =https://maps.googleapis.com/maps/api/js?key=AIzaSyC7lDrYPDmJz1JsQh2rbWA9uRZHcFk_xJY&callback=initMap> < / script>

解决方案

要更改InfoWindows,您必须禁用标记并将其添加到关联的infowindow中。

  var directionsDisplay = new google .maps.DirectionsRenderer({
suppressMarkers:true
});

标记的自定义渲染器:

  var startLocation,endLocation,waypts; 
函数RenderCustomDirections(response,status){
if(status == google.maps.DirectionsStatus.OK){
waypts = [];
var bounds = new google.maps.LatLngBounds();
var route = response.routes [0];
startLocation = new Object();
endLocation = new Object();

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;
startLocation.marker = createMarker(legs [i] .start_location,start,legs [i] .start_address,green,String.fromCharCode(A.charCodeAt(0)));
} else {
waypts [i] = new Object();
waypts [i] .latlng = legs [i] .start_location;
waypts [i] .address = legs [i] .start_address;
waypts [i] .marker = createMarker(legs [i] .start_location,waypoint+ i,legs [i] .start_address,yellow,String.fromCharCode(A.charCodeAt(0)+一世));
}
endLocation.latlng = legs [i] .end_location;
endLocation.address = legs [i] .end_address;
var steps = legs [i] .steps;
for(j = 0; j var nextSegment = steps [j] .path; (k = 0; k bounds.extend(nextSegment [k])的
;
}
}
}

endLocation.marker = createMarker(endLocation.latlng,My Company,endLocation.address,red,String.fromCharCode A.charCodeAt(0)+ waypts.length));
google.maps.event.trigger(endLocation.marker,'点击');
} else alert(status);
}

概念证明小提琴(基于此示例: http://www.geocodezip.com/v3_GoogleEx_directions-waypointsE.html



代码段:

lang =jsdata-hide =falsedata-console =truedata-babel =false>

  var map; var gmarkers = [];函数initMap(){var directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers:true}); var directionsService = new google.maps.DirectionsService; map = new google.maps.Map(document.getElementById('map'),{zoom:14,center:{lat:12.9577129,lng:77.6764937} // Starting Point Marathahalli}); directionsDisplay.setMap(地图); calculateAndDisplayRoute(directionsService,directionsDisplay);} google.maps.event.addDomListener(window,'load',initMap); function calculateAndDisplayRoute(directionsService,directionsDisplay){var selectedMode = document.getElementById('mode').value; / *配置航点* / var waypts = []; waypts.push({location:{lat:12.9583665,lng:77.6635659},// HAL中途停留:true},{location:{lat:12.9630167,lng:77.6268656},stopover:true}); directionsService.route({origin:{lat:12.9577129,lng:77.6764937},// Haight。destination:{lat:12.9868068,lng:77.6070679},// Ending Point Shivaji Nagar。travelMode:google.maps.TravelMode [selectedMode] ,waypoints:waypts},function(response,status){if(status =='OK'){directionsDisplay.setDirections(response); RenderCustomDirections(response,status);} else {window.alert('Directions requests failed to '+ status);}});}函数RenderCustomDirections(response,status){if(status == google.maps.DirectionsStatus.OK){waypts = []; var bounds = new google.maps.LatLngBounds(); var route = response.routes [0]; startLocation = new Object(); endLocation = new Object(); 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; startLocation.marker = createMarker(legs [i] .start_location,start,legs [i] .start_address,green,String.fromCharCode(A.charCodeAt(0))); } else {waypts [i] = new Object(); waypts [i] .latlng = legs [i] .start_location; waypts [i] .address = legs [i] .start_address; waypts [i] .marker = createMarker(legs [i] .start_location,waypoint+ i,legs [i] .start_address,yellow,String.fromCharCode(A.charCodeAt(0)+ i)); } endLocation.latlng = legs [i] .end_location; endLocation.address = legs [i] .end_address; var steps = legs [i] .steps; for(j = 0; j  

/ *总是明确地设置地图高度定义包含地图的div *元素的大小。 * /#map {height:100%;} / *可选:使样本页面填满窗口。 * / html,body {height:100%;保证金:0; padding:0;}#floating-panel {position:absolute;顶部:10px;左:25%; z-index:5; background-color:#fff;填充:5px;边界:1px固体#999; text-align:center; font-family:'Roboto','sans-serif'; line-height:30px; padding-left:10px;}

< script src = https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js\"></script><title>旅行中的路线方式< / title><表单ID = 了testForm > < select name =tripId> < option value =>< / option> < / select>< / form>< div id =floating-panel> < b>旅行模式:< / b> < select id =mode> < option value =DRIVING>驾驶< / option> < / select>< / div>< div id =map>< / div>


I am using google map API, it is working fine, like in this map if I click a marker, one dialogue box opens displaying the location address; instead of this I want to display a static value. How can I change my code to do this?

function initMap() {
        var directionsDisplay = new google.maps.DirectionsRenderer;
        var directionsService = new google.maps.DirectionsService;
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 14,
          center: {lat: 12.9577129, lng: 77.6764937} // Starting Point Marathahalli
        });
        directionsDisplay.setMap(map);

        calculateAndDisplayRoute(directionsService, directionsDisplay);
       
      }

      function calculateAndDisplayRoute(directionsService, directionsDisplay) {
        var selectedMode = document.getElementById('mode').value;
        
        /* configure waypoints */
        var waypts = [];
        waypts.push(
			{
              location: {lat: 12.9583665, lng: 77.6635659}, // HAL
              stopover: true
            } ,{
              location: {lat: 12.9630167, lng: 77.6268656},
              stopover: true
            }
			);
            
        directionsService.route({
          origin: {lat: 12.9577129, lng: 77.6764937},  // Haight.
          destination: {lat: 12.9868068, lng: 77.6070679},  // Ending Point Shivaji Nagar.
          travelMode: google.maps.TravelMode[selectedMode],
          waypoints: waypts
        }, function(response, status) {
          if (status == 'OK') {
            directionsDisplay.setDirections(response);
			console.log(response);
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
      }

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Travel modes in directions</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #floating-panel {
        position: absolute;
        top: 10px;
        left: 25%;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
        text-align: center;
        font-family: 'Roboto','sans-serif';
        line-height: 30px;
        padding-left: 10px;
      }
    </style>
  </head>
  <body>
  <form id="testForm">
	<select name="tripId">
		<option value=""></option>
	</select>
  </form>
  
    <div id="floating-panel">
    <b>Mode of Travel: </b>
    <select id="mode">
      <option value="DRIVING">Driving</option>
    </select>
    </div>
    <div id="map"></div>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC7lDrYPDmJz1JsQh2rbWA9uRZHcFk_xJY&callback=initMap">
    </script>

解决方案

To change the InfoWindows you have to suppress the markers and add your own with the associated infowindow.

var directionsDisplay = new google.maps.DirectionsRenderer({
  suppressMarkers: true
});

custom renderer for the markers:

var startLocation, endLocation, waypts;
function RenderCustomDirections(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {
    waypts = [];
    var bounds = new google.maps.LatLngBounds();
    var route = response.routes[0];
    startLocation = new Object();
    endLocation = new Object();

    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;
        startLocation.marker = createMarker(legs[i].start_location, "start", legs[i].start_address, "green", String.fromCharCode("A".charCodeAt(0)));
      } else {
        waypts[i] = new Object();
        waypts[i].latlng = legs[i].start_location;
        waypts[i].address = legs[i].start_address;
        waypts[i].marker = createMarker(legs[i].start_location, "waypoint" + i, legs[i].start_address, "yellow", String.fromCharCode("A".charCodeAt(0) + i));
      }
      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;
        for (k = 0; k < nextSegment.length; k++) {
          bounds.extend(nextSegment[k]);
        }
      }
    }

    endLocation.marker = createMarker(endLocation.latlng, "My Company", endLocation.address, "red", String.fromCharCode("A".charCodeAt(0) + waypts.length));
    google.maps.event.trigger(endLocation.marker, 'click');
  } else alert(status);
}

proof of concept fiddle (based off of this example: http://www.geocodezip.com/v3_GoogleEx_directions-waypointsE.html)

code snippet:

var map;
var gmarkers = [];

function initMap() {
  var directionsDisplay = new google.maps.DirectionsRenderer({
    suppressMarkers: true
  });
  var directionsService = new google.maps.DirectionsService;
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 14,
    center: {
      lat: 12.9577129,
      lng: 77.6764937
    } // Starting Point Marathahalli
  });
  directionsDisplay.setMap(map);
  calculateAndDisplayRoute(directionsService, directionsDisplay);
}
google.maps.event.addDomListener(window, 'load', initMap);

function calculateAndDisplayRoute(directionsService, directionsDisplay) {
  var selectedMode = document.getElementById('mode').value;
  /* configure waypoints */
  var waypts = [];
  waypts.push({
    location: {
      lat: 12.9583665,
      lng: 77.6635659
    }, // HAL
    stopover: true
  }, {
    location: {
      lat: 12.9630167,
      lng: 77.6268656
    },
    stopover: true
  });

  directionsService.route({
    origin: {
      lat: 12.9577129,
      lng: 77.6764937
    }, // Haight.
    destination: {
      lat: 12.9868068,
      lng: 77.6070679
    }, // Ending Point Shivaji Nagar.
    travelMode: google.maps.TravelMode[selectedMode],
    waypoints: waypts
  }, function(response, status) {
    if (status == 'OK') {
      directionsDisplay.setDirections(response);
      RenderCustomDirections(response, status);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}

function RenderCustomDirections(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {
    waypts = [];
    var bounds = new google.maps.LatLngBounds();
    var route = response.routes[0];
    startLocation = new Object();
    endLocation = new Object();

    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;
        startLocation.marker = createMarker(legs[i].start_location, "start", legs[i].start_address, "green", String.fromCharCode("A".charCodeAt(0)));
      } else {
        waypts[i] = new Object();
        waypts[i].latlng = legs[i].start_location;
        waypts[i].address = legs[i].start_address;
        waypts[i].marker = createMarker(legs[i].start_location, "waypoint" + i, legs[i].start_address, "yellow", String.fromCharCode("A".charCodeAt(0) + i));
      }
      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;
        for (k = 0; k < nextSegment.length; k++) {
          bounds.extend(nextSegment[k]);
        }
      }
    }
    endLocation.marker = createMarker(endLocation.latlng, "My Company", endLocation.address, "red", String.fromCharCode("A".charCodeAt(0) + waypts.length));
    google.maps.event.trigger(endLocation.marker, 'click');
  } else alert(status);
}

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 9,34.
  anchor: new google.maps.Point(16, 32),
  labelOrigin: new google.maps.Point(16, 10)
};

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 6,20.
      anchor: new google.maps.Point(16, 32),
      labelOrigin: new google.maps.Point(16, 10)
    };
  }
  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 20 pixels wide by 34 pixels tall.
  size: new google.maps.Size(20, 34),
  // The origin for this image is 0,0.
  origin: new google.maps.Point(0, 0),
  // The anchor for this image is at 9,34.
  anchor: new google.maps.Point(9, 34)
};
// 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, title, html, color, label) {
  var contentString = '<b>' + title + '</b><br>' + html;
  var marker = new google.maps.Marker({
    position: latlng,
    draggable: true,
    map: map,
    icon: getMarkerImage(color),
    shape: iconShape,
    title: title,
    label: label,
    zIndex: Math.round(latlng.lat() * -100000) << 5
  });
  marker.myname = title;
  gmarkers.push(marker);

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

  return marker;
}

/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto', 'sans-serif';
  line-height: 30px;
  padding-left: 10px;
}

<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<title>Travel modes in directions</title>
<form id="testForm">
  <select name="tripId">
    <option value=""></option>
  </select>
</form>
<div id="floating-panel">
  <b>Mode of Travel: </b>
  <select id="mode">
    <option value="DRIVING">Driving</option>
  </select>
</div>
<div id="map"></div>

这篇关于如何在Google地图API中发送静态消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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