使用EgMap获取用户地理位置

时间:2014-09-30 19:58:14

标签: php google-maps yii

我目前正在使用the EGmap extension for Yii。并且想知道我如何在地图加载时获得用户当前的地理位置?

这是我的代码:

Yii::app()->clientScript->registerScript('filterscript',"
        if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      alert(initialLocation)
      //map.setCenter(initialLocation);
    }, function() {
      alert(initialLocation); //alerts the lat lng
    });
  }
  // Browser doesn't support Geolocation
  else {
    alert('fail');
  }
  ",CClientScript::POS_READY);

    Yii::import('ext.EGMap.*');

            $gMap = new EGMap();
            $gMap->zoom = 5;
            $gMap->width = '100%';
            $gMap->height = 200;

            $mapTypeControlOptions = array(
                'position'=> EGMapControlPosition::RIGHT_TOP,
                'style'=>EGMap::MAPTYPECONTROL_STYLE_DEFAULT,
            );

            $gMap->mapTypeId = EGMap::TYPE_HYBRID;

            $gMap->mapTypeControlOptions= $mapTypeControlOptions;

            // Create geocoded lat and lng here
            $lat = $lng =''; 

            // Center the map on geocoded address
            $gMap->setCenter($lat, $lng);

            // Add marker on geocoded address
            $gMap->addMarker(
                new EGMapMarker($lat, $lng)
            );

            $gMap->renderMap();

如果没有使用扩展程序,请使用此工作。 (tutorial from google map api page

  var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);

  // Try W3C Geolocation (Preferred)
  if(navigator.geolocation) {
    browserSupportFlag = true;
    navigator.geolocation.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      map.setCenter(initialLocation);
    }, function() {
      handleNoGeolocation(browserSupportFlag);
    });
  }
  // Browser doesn't support Geolocation
  else {
    browserSupportFlag = false;
    handleNoGeolocation(browserSupportFlag);
  }

如何将用户lat lang标记放在地图上,因为它是从扩展程序外部完成的?我甚至做得对吗?

1 个答案:

答案 0 :(得分:2)

首先设置jsName:

$gMap->setJsName('test_map');

然后将afterInit代码添加到renderMap来电,包括上一步的名称:

$script = "
        if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      alert(initialLocation)
      test_map.setCenter(initialLocation); // <-- HERE: put name from setJsName() call
    }, function() {
      alert(initialLocation); //alerts the lat lng
    });
  }
  // Browser doesn't support Geolocation
  else {
    alert('fail');
  }
  ";

Fistst参数是其他init脚本的数组:

$gMap->renderMap(array($script));

免责声明:未经测试,但应指向正确的方向:)