添加默认位置Google地图

时间:2016-09-06 07:41:19

标签: javascript google-maps google-maps-api-3 google-maps-markers google-geocoder

我有这个脚本来计算谷歌地图上2点之间的距离并将其绘制到地图上。 但是onload map_canvas是灰色的。我想在加载时放置一个假的位置,以便在该中心打开加载的地图。

<script type="text/javascript">
// $( document ).ready(function() { 
var cnt = 1;
var autocomplete = [];
var marker = [];
var markers = [];
var usedIds = [];
var map = null;
var maxNumberOfTextboxAllowed = 5;
var insertTextboxId = [];
google.maps.event.addDomListener(window, 'load', function() {
  var places = new google.maps.places.Autocomplete(document.getElementById('source'));
  google.maps.event.addListener(places, 'place_changed', function() {
    var place = places.getPlace();
    var data = {
      "LocationName": document.getElementById("source").value,
      "lat": place.geometry.location.lat().toString(),
      "lng": place.geometry.location.lng().toString()
    };

    if (markers.length > 0) {
      markers.splice(0, 1, data);
    } else
      markers.splice(0, 0, data); // splice(position, numberOfItemsToRemove, item)
      initialize();
  });
  var places1 = new google.maps.places.Autocomplete(document.getElementById('destination'));
  google.maps.event.addListener(places1, 'place_changed', function() {
    var place1 = places1.getPlace();
    var data = {
      "LocationName": document.getElementById("destination").value,
      "lat": place1.geometry.location.lat().toString(),
      "lng": place1.geometry.location.lng().toString()
    }
    if (markers.length == 1) {
      markers.splice(1, 1, data);
    } else if (markers.length > 0)
      markers.splice(markers.length - 1, 1, data)
      initialize();
  });
});
// });
function GenerateSourceDestinationPoint() {
  if (cnt <= maxNumberOfTextboxAllowed) {
    var fieldWrapper = $("<div class='fieldwrapper' id='field" + cnt + "'/>");
    var valueStr;
    if (cnt == 1) {
      valueStr = "Cardiff, UK";
    } else if (cnt == 2) {
      valueStr = "Newport, UK";
    } else if (cnt == 3) {
      valueStr = "Bath, UK";
    } else {
      valueStr = "";
    }
    var fName = $("<input type='text' class='fieldname' id='Txtopt" + cnt + "'  name='TxtoptNm" + cnt + "' value='" + valueStr + "' />");
    fieldWrapper.append(fName);
    fieldWrapper.append('<br />');
    fieldWrapper.append('<br />');
    $("#abc").append(fieldWrapper);
    var newInput = [];
    var newEl = document.getElementById('Txtopt' + cnt);
    var txtboxId = 'Txtopt' + cnt;
    newInput.push(newEl);
    setupAutocomplete(autocomplete, newInput, 0, txtboxId);
    cnt = cnt + 1;
  } else
    alert("Cant create more than 5 textbox");
}
function setupAutocomplete(autocomplete, inputs, i, txtboxId) {
  insertTextboxId.push(txtboxId);
  autocomplete.push(new google.maps.places.Autocomplete(inputs[i]));
  var idx1 = autocomplete.length - 1;
  var idx = markers.length - 1;
  markers[idx + 1] = markers[idx];
  markers[idx] = {};
  google.maps.event.addListener(autocomplete[idx1], 'place_changed', function() {
    var pos = idx1 + 1;
    var place = autocomplete[idx1].getPlace();
    if (!place.geometry) {
      return;
    }
    var autoTextbox = {
      "LocationName": document.getElementById(insertTextboxId[idx1]).value,
      "lat": autocomplete[idx1].getPlace().geometry.location.lat().toString(),
      "lng": autocomplete[idx1].getPlace().geometry.location.lng().toString()
    }
    markers[idx] = autoTextbox;
    initialize();
  });
}
function initialize() {
  var bounds = new google.maps.LatLngBounds();
  var mapOptions = {
    center: new google.maps.LatLng(parseFloat(markers[0].lat), parseFloat(markers[0].lng)),
    zoom: 10,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var path = new google.maps.MVCArray();
  var service = new google.maps.DirectionsService();
  var infoWindow = new google.maps.InfoWindow();
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  var poly = new google.maps.Polyline({
    map: map,
    strokeColor: '#F3443C'
  });
  var lat_lng = [];
  var marker = new google.maps.Marker({
    position: map.getCenter(),
    map: map
  });
  bounds.extend(marker.getPosition());
  var src, des;
  var waypoints = [];
  for (var i = 0; i < markers.length; i++) {
    if (i === 0) {
      src = new google.maps.LatLng(parseFloat(markers[i].lat),
        parseFloat(markers[i].lng));
      var smarker = new google.maps.Marker({
        position: src,
        map: map
      });
      bounds.extend(smarker.getPosition());
    } else if (i == markers.length - 1) {
      des = new google.maps.LatLng(parseFloat(markers[i].lat),
        parseFloat(markers[i].lng));
      var dmarker = new google.maps.Marker({
        position: des,
        map: map
      });
      bounds.extend(dmarker.getPosition());
    } else {
      var latlng = new google.maps.LatLng(markers[i].lat, markers[i].lng);
      waypoints.push({
        location: latlng,
        stopover: true
      });
      var marker = new google.maps.Marker({
        position: latlng,
        map: map
      });
    }
  }
  service.route({
    origin: src,
    destination: des,
    waypoints: waypoints,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  }, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
        path.push(result.routes[0].overview_path[i]);
      }
      poly.setPath(path);
      map.fitBounds(bounds);
    }
  });
}
  </script>

2 个答案:

答案 0 :(得分:0)

初始化地图后尝试使用此代码段(13是缩放级别)

map.setCenter(new google.maps.LatLng(position.coords.latitude, 
                                 position.coords.longitude), 13);

您也可以使用HTML5地理定位服务

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(success, error);
}

function success(position) {
     map.setCenter(new google.maps.LatLng(position.coords.latitude, 
                                 position.coords.longitude), 13);
}

function error(msg) {
   alert(msg);
}

答案 1 :(得分:0)

onload功能中初始化地图。

google.maps.event.addDomListener(window, 'load', function() {  
var mapOptions = {
  center: new google.maps.LatLng(0,0),
  zoom: 2
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

proof of concept fiddle

代码段

&#13;
&#13;
var cnt = 1;
var autocomplete = [];
var marker = [];
var markers = [];
var usedIds = [];
var map = null;
var maxNumberOfTextboxAllowed = 5;
var insertTextboxId = [];
google.maps.event.addDomListener(window, 'load', function() {
  // initialize map
  var mapOptions = {
    center: new google.maps.LatLng(0, 0),
    zoom: 2
  };
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  
  var places = new google.maps.places.Autocomplete(document.getElementById('source'));
  google.maps.event.addListener(places, 'place_changed', function() {
    var place = places.getPlace();
    var data = {
      "LocationName": document.getElementById("source").value,
      "lat": place.geometry.location.lat().toString(),
      "lng": place.geometry.location.lng().toString()
    };

    if (markers.length > 0) {
      markers.splice(0, 1, data);
    } else
      markers.splice(0, 0, data); // splice(position, numberOfItemsToRemove, item)
    initialize();
  });
  var places1 = new google.maps.places.Autocomplete(document.getElementById('destination'));
  google.maps.event.addListener(places1, 'place_changed', function() {
    var place1 = places1.getPlace();
    var data = {
      "LocationName": document.getElementById("destination").value,
      "lat": place1.geometry.location.lat().toString(),
      "lng": place1.geometry.location.lng().toString()
    }
    if (markers.length == 1) {
      markers.splice(1, 1, data);
    } else if (markers.length > 0)
      markers.splice(markers.length - 1, 1, data)
    initialize();
  });
});
// });
function GenerateSourceDestinationPoint() {
  if (cnt <= maxNumberOfTextboxAllowed) {
    var fieldWrapper = $("<div class='fieldwrapper' id='field" + cnt + "'/>");
    var valueStr;
    if (cnt == 1) {
      valueStr = "Cardiff, UK";
    } else if (cnt == 2) {
      valueStr = "Newport, UK";
    } else if (cnt == 3) {
      valueStr = "Bath, UK";
    } else {
      valueStr = "";
    }
    var fName = $("<input type='text' class='fieldname' id='Txtopt" + cnt + "'  name='TxtoptNm" + cnt + "' value='" + valueStr + "' />");
    fieldWrapper.append(fName);
    fieldWrapper.append('<br />');
    fieldWrapper.append('<br />');
    $("#abc").append(fieldWrapper);
    var newInput = [];
    var newEl = document.getElementById('Txtopt' + cnt);
    var txtboxId = 'Txtopt' + cnt;
    newInput.push(newEl);
    setupAutocomplete(autocomplete, newInput, 0, txtboxId);
    cnt = cnt + 1;
  } else
    alert("Cant create more than 5 textbox");
}

function setupAutocomplete(autocomplete, inputs, i, txtboxId) {
  insertTextboxId.push(txtboxId);
  autocomplete.push(new google.maps.places.Autocomplete(inputs[i]));
  var idx1 = autocomplete.length - 1;
  var idx = markers.length - 1;
  markers[idx + 1] = markers[idx];
  markers[idx] = {};
  google.maps.event.addListener(autocomplete[idx1], 'place_changed', function() {
    var pos = idx1 + 1;
    var place = autocomplete[idx1].getPlace();
    if (!place.geometry) {
      return;
    }
    var autoTextbox = {
      "LocationName": document.getElementById(insertTextboxId[idx1]).value,
      "lat": autocomplete[idx1].getPlace().geometry.location.lat().toString(),
      "lng": autocomplete[idx1].getPlace().geometry.location.lng().toString()
    }
    markers[idx] = autoTextbox;
    initialize();
  });
}

function initialize() {
  var bounds = new google.maps.LatLngBounds();
  var mapOptions = {
    center: new google.maps.LatLng(parseFloat(markers[0].lat), parseFloat(markers[0].lng)),
    zoom: 10,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var path = new google.maps.MVCArray();
  var service = new google.maps.DirectionsService();
  var infoWindow = new google.maps.InfoWindow();
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  var poly = new google.maps.Polyline({
    map: map,
    strokeColor: '#F3443C'
  });
  var lat_lng = [];
  var marker = new google.maps.Marker({
    position: map.getCenter(),
    map: map
  });
  bounds.extend(marker.getPosition());
  var src, des;
  var waypoints = [];
  for (var i = 0; i < markers.length; i++) {
    if (i === 0) {
      src = new google.maps.LatLng(parseFloat(markers[i].lat),
        parseFloat(markers[i].lng));
      var smarker = new google.maps.Marker({
        position: src,
        map: map
      });
      bounds.extend(smarker.getPosition());
    } else if (i == markers.length - 1) {
      des = new google.maps.LatLng(parseFloat(markers[i].lat),
        parseFloat(markers[i].lng));
      var dmarker = new google.maps.Marker({
        position: des,
        map: map
      });
      bounds.extend(dmarker.getPosition());
    } else {
      var latlng = new google.maps.LatLng(markers[i].lat, markers[i].lng);
      waypoints.push({
        location: latlng,
        stopover: true
      });
      var marker = new google.maps.Marker({
        position: latlng,
        map: map
      });
    }
  }
  service.route({
    origin: src,
    destination: des,
    waypoints: waypoints,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  }, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
        path.push(result.routes[0].overview_path[i]);
      }
      poly.setPath(path);
      map.fitBounds(bounds);
    }
  });
}
&#13;
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="source" />
<input id="destination" />
<div id="map_canvas"></div>
&#13;
&#13;
&#13;