使用数据库中的坐标在地图上添加标记,使用 JSON 检索数据

Posted

技术标签:

【中文标题】使用数据库中的坐标在地图上添加标记,使用 JSON 检索数据【英文标题】:Add markers on Map using coordinates from database, retrieving data with JSON 【发布时间】:2020-04-10 21:55:39 【问题描述】:

我正在尝试开发一个在 MapReady 上添加标记的应用程序,该标记具有从数据库中检索到的坐标。到目前为止,为了将数据发送到数据库(注册/登录/获取配置文件)等,我使用了JSON。现在我正在尝试以相同的方式从数据库中获取纬度和经度,但调试器在调用 Json 方法后显示变量为 Null。另外,我想问一下我应该如何放置标记的一些指导?我的意思是,用JSONObject 获取坐标,它会给我表格中的所有行吗?还是我必须使用其他方法来获取所有行并为每一行添加标记?谢谢!

在 onMapReady 结束时调用 AddMarker 以获取坐标,以便我可以添加标记:

 private void AdaugaMarker() 

    class AdaugaMarker extends AsyncTask<Void, Void, String> 

        @Override
        protected String doInBackground(Void... voids) 
            //creating request handler object
            RequestHandler requestHandler = new RequestHandler();

            //creating request parameters
            HashMap<String, String> params = new HashMap<>();
            params.put("problema", finalProblema);

            //returing the response
            return requestHandler.sendPostRequest(URLs.URL_GETALERTE, params);
        

        @Override
        protected void onPreExecute() 
            super.onPreExecute();
            //displaying the progress bar while user registers on the server
        

        @Override
        protected void onPostExecute(String s) 
            super.onPostExecute(s);
            //hiding the progressbar after completion

            try 
                //converting response to json object
                JSONObject obj = new JSONObject(s);

                //if no error in response
                if (!obj.getBoolean("error")) 
                    Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

                    //getting the user from the response
                    JSONObject userJson = obj.getJSONObject("locatie");

                    latitudine_sql =Double.valueOf(userJson.getString("latitudine"));
                    longitudine_sql = Double.valueOf(userJson.getString("longitudine"));
                    tip_problema_sql = userJson.getString("tip_problema");
                 else 
                    Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
                
             catch (JSONException e) 
                e.printStackTrace();
            
        
    

    //executing the async task
    AdaugaMarker ru = new AdaugaMarker();
    ru.execute();

.php 由 URL_GETALERTE 调用:

case 'getAlerte':

            if(isTheseParametersAvailable(array('problema')))

                $problema = $_POST['problema'];

                $stmt = $conn->prepare("SELECT latitudine, longitudine, tip_problema FROM alerte WHERE tip_problema = ?");
                $stmt->bind_param("s", $problema);
                $stmt->execute();
                $stmt->store_result(); 
                if($stmt->num_rows > 0)
                $stmt->bind_result($latitudine, $longitudine, $problema);
                        $stmt->fetch();

                        $locatie = array(
                            'latitudine'=>$latitudine,
                            'longitudine'=>$longitudine,
                            'tip_problema'=>$problema

                        );
                    $response['error'] = false; 
                    $response['message'] = 'Alerta raportata';
                    $response['locatie'] = $locatie;    
                else   
                    $response['error'] = true; 
                    $response['message'] = 'Eroare de identificare a alertelor';
                               
                else
                    $response['error'] = false; 
                    $response['message'] = 'Alerta nu a putut fi raportata';
                
            break;

在.php的开头我添加了$response = array();

编辑: 添加 JSONArray:

//converting response to json object
                JSONObject obj = new JSONObject(s);

                //if no error in response
                if (!obj.getBoolean("error")) 
                    Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

                    JSONArray locatieArray = obj.getJSONArray("locatie");
                    for (int i = 0; i < locatieArray.length(); i++) 
                        JSONObject locatie = locatieArray.getJSONObject(i);
                        // check latitudine and longitudine is not null and if not null then cast these values and call the addMarker() method.
                        if(!locatie.isNull("latitudine") && !locatie.isNull("longitudine")) 
                            latitudine_sql =Double.valueOf(locatie.getString("latitudine"));
                            longitudine_sql = Double.valueOf(locatie.getString("longitudine"));
                            addMarker(latitudine_sql, longitudine_sql); // this method is implemented below
                        
                        tip_problema_sql = locatie.getString("tip_problema");
                    

                 else 
                    Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
                
             catch (JSONException e) 
                e.printStackTrace();
            

【问题讨论】:

【参考方案1】:

您正在接收纬度和经度的 JSONArray,但您正在解析为 JSONObject。 //先创建这个类

public class Locatie 
private Double latitudine;

private String tip_problema;

private Double longitudine;

public Double getLatitudine() 
    return latitudine;


public void setLatitudine(Double latitudine) 
    this.latitudine = latitudine;


public String getTip_problema() 
    return tip_problema;


public void setTip_problema(String tip_problema) 
    this.tip_problema = tip_problema;


public Double getLongitudine() 
    return longitudine;


public void setLongitudine(Double longitudine) 
    this.longitudine = longitudine;


@Override
public String toString() 
    return "ClassPojo [latitudine = " + latitudine + ", tip_problema = " + tip_problema + ", longitudine = " + longitudine + "]";

 if (!obj.getBoolean("error")) 
            ArrayList<Locatie> locatieList = new ArrayList<>();
            Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

            //getting the user from the response
            JSONArray userLatLngArray = obj.getJSONArray("locatie");
            for (int i = 0; i < userLatLngArray.length(); i++) 
                Locatie locate = new Locatie();
                JSONObject data = userLatLngArray.getJSONObject[i];


                //Here you need to create List of POJO class to save all lat log values in list so //you can access any where.
                locate.setLatitudine(Double.valueOf(data.getString("latitudine")));
                locate.longitudine_sql(Double.valueOf(data.getString("longitudine")));
                locate.setLatitudine(data.getString("tip_problema"));

                locatieList.add(locate);

                //locatieList will be arraylist of lat lng pojo

            

         else 
            Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
        

【讨论】:

我已经尝试了这两个答案,但导致错误的情况位于.php中。从android的角度来看,这两个答案都是正确的。谢谢!【参考方案2】:

试试这个方法

//if no error in response
if (!obj.getBoolean("error")) 
    Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

    //getting the user from the response
    JSONObject userJson = obj.getJSONObject("locatie");

    // check latitudine and longitudine is not null and if not null then cast these values and call the addMarker() method. 
    if(!userJson.isNull("latitudine") && !userJson.isNull("longitudine")) 
        latitudine_sql =Double.valueOf(userJson.getString("latitudine"));
        longitudine_sql = Double.valueOf(userJson.getString("longitudine"));

        addMarker(latitudine_sql, longitudine_sql); // this method is implemented below
    
    tip_problema_sql = userJson.getString("tip_problema");

 else 
    Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();

private void addMarker(double latitude, double longitude)
   LatLng position = new LatLng(latitude, longitude);

   // Instantiating MarkerOptions class
   MarkerOptions options = new MarkerOptions();

   // Setting position for the MarkerOptions
   options.position(position);

   // Setting title for the MarkerOptions
   options.title("Position");

   // Setting snippet for the MarkerOptions
   options.snippet("Latitude:"+latitude+",Longitude:"+longitude);

   // Adding Marker on the Google Map
   googleMap.addMarker(options); // make sure you have initialized googleMap

   // Creating CameraUpdate object for position
   CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(position);

   // Creating CameraUpdate object for zoom
   CameraUpdate updateZoom = CameraUpdateFactory.zoomBy(4);

   // Updating the camera position to the user input latitude and longitude
   googleMap.moveCamera(updatePosition);

   // Applying zoom to the marker position
   googleMap.animateCamera(updateZoom);

更新:

对于多个标记

// get locatie as JsonArray
JSONArray locatieArray = obj.getJSONArray("locatie");
for (int i = 0; i < locatieArray.length(); i++) 
      JSONObject locatie = locatieArray.getJSONObject[i];

      // check latitudine and longitudine is not null and if not null then cast these values and call the addMarker() method. 
      if(!locatie.isNull("latitudine") && !locatie.isNull("longitudine")) 
          latitudine_sql =Double.valueOf(userJson.getString("latitudine"));
          longitudine_sql = Double.valueOf(userJson.getString("longitudine"));

          addMarker(latitudine_sql, longitudine_sql); // this method is implemented below
      
      tip_problema_sql = userJson.getString("tip_problema");

【讨论】:

首先,从 php.ini 中检索出现错误。 latitudine_sql 得到 Double.valueOf(userJson.getString("latitudine")); 后为空,经度也为空 好吧,你可以通过检查userJson.isNull("latitudine")来绕过错误。查看我的更新答案。 您不能将null 转换为intdouble。因此,在转换为 intfloatdouble 之前,您必须正确检查并确保值不是 null 我已经尝试过了,它现在可以工作了,但是应用程序在地图上只添加了 1 个标记 = 表格中的 1 行,而不是全部。 看到这个了解邮递员youtube.com/watch?v=t5n07Ybz7yI

以上是关于使用数据库中的坐标在地图上添加标记,使用 JSON 检索数据的主要内容,如果未能解决你的问题,请参考以下文章

如何使用我的 JSON 数据在谷歌地图 API 上创建标记?

在谷歌地图标记上显示信息

百度地图的坐标怎么添加啊?

如何在 Mapbox iOS 中的特定坐标上放置自定义注释的底部

谷歌地图 API。添加标记

如何在谷歌地图上添加多个标记