微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 使用EgMap获取用户地理位置

我目前正在使用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 marker放在地图上,因为它是从扩展程序外部完成的?我甚至做得对吗?

解决方法:

首先设置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));

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐