我正在使用下面的代码。当我的用户登录并输入地址时,我想在地图上显示他们的位置。
<?php
// Get lat and long by address
$dlocation = '2286 Wellman Place,Oak Harbor,WA';
$address = $dlocation; // Google HQ
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$latitude = $output->results[0]->geometry->location->lat;
$longitude = $output->results[0]->geometry->location->lng;
echo $latitude;
?>
<html>
<head>
<style type="text/css">
div#map {
position: relative;
}
div#crosshair {
position: absolute;
top: 192px;
height: 19px;
width: 19px;
left: 50%;
margin-left: -8px;
display: block;
/* background: url(crosshair.gif); */
background-position: center center;
background-repeat: no-repeat;
}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var geocoder;
var centerChangedLast;
var reverseGeocodedLast;
var currentReverseGeocodeResponse;
function initialize() {
var latlng = new google.maps.LatLng(48.258545,-122.7399284);
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Hello World!"
});
}
</script>
</head>
<body onload="initialize()">
<div id="map" style="width:700px; height:800px">
<div id="map_canvas" style="width:100%; height:800px"></div>
<div id="crosshair"></div>
</div>
</body>
</html>
当我尝试用变量 $latitude 和 $longitude 替换 48.258545,-122.7399284 时,地图不会加载。 我需要改变什么才能让它起作用。
如果你想在 javascript 中使用 php 变量,你必须回显结果
function initialize() {
var latlng = new google.maps.LatLng(<?= $latitude . ',' . $longitude ?>);
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
或将 php var 值分配给 javascript vars
<script type="text/javascript">
var map;
var geocoder;
var centerChangedLast;
var my_latitude = <?= $latitude ?>;
var my_longitude = <?= $longitude ?>;
.......
.....
function initialize() {
var latlng = new google.maps.LatLng(my_latitude , my_longitude );
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};